很抱歉,如果以前有人问过这个问题,但我想根据另一个数组的标准对javascript数组进行排序。我知道criteria数组中包含的所有值都将在某个地方的较大数组中,但是我需要将criteria数组中的值移到列表顶部。
例如,我有一个更大的数组,看起来像这样:
array = [
{_id: "123", username: "username1",platform: "xbox"},
{_id: "124", username: "username2",platform: "xbox"},
{_id: "125", username: "username3",platform: "ps4"},
{_id: "126", username: "username4",platform: "pc"},
{_id: "127", username: "username5",platform: "ps4"},
{_id: "128", username: "username6",platform: "pc"}
];
然后我需要根据较小数组的标准对较大数组进行排序,然后将这些值移至较大数组的顶部
因此,在这种情况下,条件数组将为
critarray = [
{_id: "124", username: "username2",platform: "xbox"},
{_id: "127", username: "username5",platform: "ps4"},
{_id: "128", username: "username6",platform: "pc"},
];
较大的数组将按以下顺序排序:
array = [
{_id: "124", username: "username2",platform: "xbox"},
{_id: "127", username: "username5",platform: "ps4"},
{_id: "128", username: "username6",platform: "pc"},
{_id: "123", username: "username1",platform: "xbox"},
{_id: "125", username: "username3",platform: "ps4"},
{_id: "126", username: "username4",platform: "pc"},
];
只要条件数组中的所有对象都移到顶部,顺序也不重要。
任何帮助将不胜感激!
谢谢
答案 0 :(得分:0)
过滤并合并
由于您除了关心这两个组之外的其他顺序之外,而且您知道较大的数组具有较小数组中的所有元素,而不是进行排序,因此可以将所有critarray
个项目从{{ 1}}而非串联array
和critarray
:
array
这假设let array = [
{_id: "123", username: "username1",platform: "xbox"},
{_id: "124", username: "username2",platform: "xbox"},
{_id: "125", username: "username3",platform: "ps4"},
{_id: "126", username: "username4",platform: "pc"},
{_id: "127", username: "username5",platform: "ps4"},
{_id: "128", username: "username6",platform: "pc"}
];
let critarray = [
{_id: "124", username: "username2",platform: "xbox"},
{_id: "127", username: "username5",platform: "ps4"},
{_id: "128", username: "username6",platform: "pc"},
];
// all items not in crit array
let arrayFiltered = array.filter(item => !critarray.find(i => i._id === item._id) )
// concat critarray first, then rest
let newArr = critarray.concat(arrayFiltered)
console.log(newArr)
是唯一标识符。
或排序
或者,您也可以从_id
中创建一个Set
的ID,如果要对数组进行排序,则可以使用该集合中的包含作为排序的基础:
citarray