在 JavaScript 中将特定元素推送到最后
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/9 7:40: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/

