我有两个选定的对象数组和我们正在显示的其他一般数据
General data for display
const arr = [
{
id: "1",
name: "Skoda - Auto"
},
{
id: "2",
name: "BMW - Auto"
},
{
id: "3",
name: "Mustang"
},
{
id: "2",
name: "Ferrari"
},
{
id: "1",
name: "Ford"
}
];
selectedValues
const selectedArr = [
{
id: "1",
name: "something - 1"
},
{
id: "3",
name: "something - 1"
}
]
我想根据这个选定的数组对一般数据进行排序以进行显示。所以基本上我想匹配来自 selectedArr 的 id,检查此 id 是否存在于通用数组中,如果是,则对通用数组进行洗牌,以便所选值位于数组的顶部 欧/普
const arr = [
{
id: "1",
name: "Skoda - Auto"
},
{
id: "1",
name: "Ford"
},
{
id: "3",
name: "Mustang"
},
{
id: "2",
name: "BMW - Auto"
},
{
id: "2",
name: "Ferrari"
},
];
有多个具有相同 id 的值,如果选定数组中存在这些值,我需要取消移动顶部的这些值。我不确定如何实现这样的输出,因此需要一些帮助
这可以通过将排序数组索引到一个映射中来实现,该映射为给定的
id
提供索引:
const selectedArr = [
{
id: "1",
name: "something - 1"
},
{
id: "3",
name: "something - 1"
}
]
const sortMap = new Map(selectedArr.map(({ id }, idx) => [id, idx]));
然后在标准
sort
函数中使用它:
const sortedArray = [...arr].sort(
(a, b) => (sortMap.get(a.id) ?? 10000000) - (sortMap.get(b.id) ?? 10000000)
);
一种效率不高但简单的方法是对数组进行两次过滤,创建一个包含所选元素的数组和一个不包含所选元素的数组,然后将这两个数组连接在一起,如下例所示。
const selected = [4, 8, 3];
const fullArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sorted = fullArray.filter((e) => selected.includes(e))
.concat(fullArray.filter((e) => !selected.includes(e)));
console.log(sorted);