将特定元素推送到JavaScript中
假设我们有一个这样的对象数组-
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 }
]热门推荐
2 红丝绒戚风蛋糕
3 夹心小甜点
4 南瓜甜点
6 粘米粉蒸蛋糕
7 酸奶华夫饼
9 红柚鸡蛋糕
10 葡萄干蛋糕
11 紫薯蛋糕卷
13 纸杯裱花小蛋糕
14 果酱奶酪蛋糕
15 日式樱花蔓越莓大福
16 草莓蛋糕卷
17 卡仕达长崎杯子蛋糕