我有一个数组
const arr = [
{label: 'a', width: 200},
{label: 'b', width: 200},
{label: 'c', width: 200},
{label: 'd', width: 200},
{label: 'e', width: 200}
];
给定另一个阵列
const data = ['d', 'e', 'a', 'c', 'b'];
它需要根据新数据重新排列第一个数组。
我应该在javascript中使用什么函数?
编辑:谢谢你非常有趣的评论。但为了使其更加复杂,我们假设数据也可能不是第一个数组的完整列表。
const data = ['a', 'c'];
并且它仍然应该产生第一个数组,其中前两个元素是a&c、 剩下的是b、d、e。完成的数组应该在a、c、b、d、e的列表中。
- 使用
Array#reduce
,在data
上迭代以将元素索引保存在Map
中 - 使用
Array#sort
,根据上面Map中每个元素的值对arr
进行排序
const sort = (arr = [], data = []) => {
const indicesMap = data.reduce((map, e, i) => map.set(e, i), new Map);
return [...arr].sort(({ label: a}, { label: b }) => {
const indexA = indicesMap.get(a), indexB = indicesMap.get(b);
return (indexA === undefined || indexB === undefined)
? isNaN(indexA) - isNaN(indexB)
: indexA - indexB;
});
}
const arr = [ {label: 'a', width: 200}, {label: 'b', width: 200}, {label: 'c', width: 200}, {label: 'd', width: 200}, {label: 'e', width: 200} ];
console.log( sort(arr, ['d', 'e']) );
console.log( sort(arr, ['a', 'd']) );
console.log( sort(arr, ['d', 'e', 'a', 'c', 'b']) );
const arr = [
{ label: "a", width: 200 },
{ label: "b", width: 200 },
{ label: "c", width: 200 },
{ label: "d", width: 200 },
{ label: "e", width: 200 }
];
const data = ["d", "e", "a", "c", "b"];
const updatedArray = data.map((item) => arr.find((t) => t.label === item));
console.log(updatedArray);
简单地说:
const arr =
[ { label: 'a', width: 200}
, { label: 'b', width: 200}
, { label: 'c', width: 200}
, { label: 'd', width: 200}
, { label: 'e', width: 200}
]
const data = ['d', 'e', 'a', 'c', 'b']
arr.sort((a, b) => data.indexOf(a.label) - data.indexOf(b.label))
console.log(arr)
要解决这个问题,请使用map()和find()方法,如下所示:
const sorted = data.map(element => arr.find(obj => obj.label === element))
这里有一个使用排序的简短解决方案
const arr = [
{label: 'a', width: 200},
{label: 'b', width: 200},
{label: 'c', width: 200},
{label: 'd', width: 200},
{label: 'e', width: 200}
];
const data = ['d', 'e', 'a', 'c', 'b'];
const sorted = arr.sort(function(a, b){
return data.indexOf(a.label) - data.indexOf(b.label);
});
console.log(sorted)
您可以将排序后的数组的顺序作为权重并对数组进行排序。
const arr = [
{label: 'a', width: 200},
{label: 'b', width: 200},
{label: 'c', width: 200},
{label: 'd', width: 200},
{label: 'e', width: 200}
];
const sortOrder = ['d', 'e', 'a', 'c', 'b'];
arr.sort((x, y) => sortOrder.indexOf(x.label) - sortOrder.indexOf(y.label))
console.log(arr)