我正在尝试根据特定值对数组项进行排序。我的数组值如下
var items = [
{color: "red" …}
{color: "green" …}
{color: "orange" …}
{color: "blue" …}
]
我想要实现的是
["blue, red, green, orange"]
只有指定值(即“蓝色”)应该是第一项,其余数组项应保留其实际顺序。
这是我到目前为止的代码
items.sort((a, b) =>
(b.color === 'blue') - (a.color === 'blue') || a.color.localeCompare(b.color))
上面的代码根据需要将项目“蓝色”排序到顶部,但其余项目的顺序不正确
["blue, green, red, orange"]
然而,想要的结果是
["blue, red, green, orange"]
const items = [{color: "red"}, {color: "blue"}, {color: "green"}, {color: "orange"}, {color: "blue"}];
const orderedColorsArr = [
...items.filter(({color}) => color==="blue"),
...items.filter(({color}) => color!=="blue")
].map(({color}) => color);
const res = [orderedColorsArr.join(", ")];
console.log(res)
首先,您需要一个包含颜色的数组,然后需要访问字符串而不是未给定的属性,然后仅按与所需顶部颜色的比较的增量进行排序。
const
items = [{ color: "red" }, { color: "green" }, { color: "orange" }, { color: "blue" }]
items.sort((a, b) => (b.color === 'blue') - (a.color === 'blue'));
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
对于不稳定的环境
const
items = [{ color: "red" }, { color: "green" }, { color: "orange" }, { color: "blue" }],
order = items.reduce((m, o, i) => m.set(o, i + 1), new Map);
items.sort((a, b) =>
(b.color === 'blue') - (a.color === 'blue') ||
order.get(a) - order.get(b)
);
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
嗯,看来您没有在这里对任何东西进行排序。那么为什么还要使用排序呢?
尝试从indexOf函数获取索引后拼接“蓝色”元素,然后将其插入数组的开头。
let items= [
{color: "red"},
{color: "green"},
{color: "orange"},
{color: "blue"}
];
const removedElement = items.splice(items.indexOf({color: "blue"}),1);
//or alternatively items.unshift(removedElement[0])
items= [...removedElement,...items].map(item=> item.color).join(",");
const result = [items]
console.log(result);
//["blue,red,green,orange"]
您可以采取的另一种方法是,过滤掉非蓝色元素,过滤掉蓝色元素,然后用这两个元素创建一个新数组。
const result = [[...items.filter(item => item.color==="blue"), ...items.filter(item => item.color!=="blue")].map(item=>item.color).join(",")];
console.log(result);
// ["blue,red,green,orange"]
Most easiest way is to map and filter without mutation main array
let items= [
{color: "red"},
{color: "green"},
{color: "orange"},
{color: "blue"}
];
const newarr=[];
const arr = items.filter(el=>el.color=="blue"?newarr.push({color:"blue"}):el);
const arr1 = items.filter(el=>el.color!=="blue"?newarr.push(el):"");
console.log(newarr.map(el=>el.color))