对数组进行排序,使特定项在数组中排在第一位 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/2 1:48:17
假设,我们有一个像这样的对象数组 −
const arr = [
{flag: true, other: 1},
{flag: true, other: 2},
{flag: false, other: 3},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6},
{flag: false, other: 7}
];
我们需要编写一个 JavaScript 函数,该函数接受一个这样的数组并根据以下条件对其进行排序 −
- 如果 arr.flag === false,则匹配元素将放在数组的第一位,但只能放在前一个匹配元素之后。
- 不匹配的元素保持其原始顺序。
- 出现顺序很重要。
因此,对于上述数组,输出应该是 −
const output = [
{flag: false, other: 3},
{flag: false, other: 7},
{flag: true, other: 1},
{flag: true, other: 2},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6}
];
示例
以下是代码 −
const arr = [
{flag: true, other: 1},
{flag: true, other: 2},
{flag: false, other: 3},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6},
{flag: false, other: 7}
];
const sortByFlag = arr => {
const sorter = (a, b) => {
if(!a['flag'] && b['flag']){
return -1;
};
if(a['flag'] && !b['flag']){
return 1;
}
return a['other'] - b['other'];
}
arr.sort(sorter);
};
sortByFlag(arr);
console.log(arr);
输出
这将在控制台上产生以下输出 −
[
{ flag: false, other: 3 },
{ flag: false, other: 7 },
{ flag: true, other: 1 },
{ flag: true, other: 2 },
{ flag: true, other: 4 },
{ flag: true, other: 5 },
{ flag: true, other: 6 }
]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

