gpt4 book ai didi

javascript - 使用其他数组对数组对象进行排序

转载 作者:行者123 更新时间:2023-12-01 00:35:25 29 4
gpt4 key购买 nike

无法根据给定数组对数组对象进行排序你能帮我一下吗!!

reference link

const data = [ {
parent_email: 'testuser@mailinator.com',
childSurName: null,
childFirstName: null,
id: 22},
{
parent_email: 'p20@mailinator.com',
childSurName: null,
childFirstName: 'Sachidanand',
id: 31},
{
parent_email: 'aa@aa.aaa',
childSurName: null,
childFirstName: null,
id: 26}];

const order = [ 31,26 ];

const sorted = data.sort((a, b) => (
order.indexOf(a.id) - order.indexOf(b.id)
));

console.log(sorted)

我需要像我的第二个数组一样的排序结果,然后在其他数据之后:

 [ {
parent_email: 'p20@mailinator.com',
childSurName: null,
childFirstName: 'Sachidanand',
id: 31},
{
parent_email: 'aa@aa.aaa',
childSurName: null,
childFirstName: null,
id: 26}
{
parent_email: 'testuser@mailinator.com',
childSurName: null,
childFirstName: null,
id: 22},
];

但我得到的结果低于未获得正确排序数据的结果:

[{
parent_email:"testuser@mailinator.com",
childSurName:null,
childFirstName:null,
id:22
},
{
parent_email:"p20@mailinator.com",
childSurName:null,
childFirstName:"Sachidanand",
id:31
},
{
parent_email:"aa@aa.aaa",
childSurName:null,
childFirstName:null,
id:26
}]

最佳答案

您可以使用Map并在Map中放置值和优先级,然后排序,

注意:- 另外不要忘记保持搜索值和键相同类型

const data = [{parent_email: 'testuser@mailinator.com',childSurName: null,childFirstName: null,id: 22},{parent_email: 'p20@mailinator.com',childSurName: null,childFirstName: 'Sachidanand',id: 31},{parent_email: 'aa@aa.aaa',childSurName: null,childFirstName: null,id: 26}];

const order = ['31', '22'];
const mapper = new Map(order.map((v, i) => [parseInt(v), i + 1]))

const sorted = data.sort((a, b) => (
(mapper.get(a.id) || Infinity) - (mapper.get(b.id) || Infinity)
));

console.log(sorted)

关于javascript - 使用其他数组对数组对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58164895/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com