gpt4 book ai didi

javascript - 根据嵌套对象值对数组进行排序

转载 作者:行者123 更新时间:2023-12-04 15:10:08 24 4
gpt4 key购买 nike

我正在尝试创建一个根据嵌套对象值对数组进行排序的函数。

const customers = [
{
name: 'John',
displayOrder: [{ route1: 1 }, { route2: 3 }],
},
{
name: 'Julie',
displayOrder: [{ route1: 2 }, { route2: 1 }],
},
{
name: 'Betsy',
displayOrder: [{ route1: 3 }, { route2: 2 }],
},
];

function sortCustomers(customers, route) {
//enter amazing code here :P
//here is what I think could work, just don't know how to get the index number
customers.sort((a, b) => (a.displayOrder[?].route > b.displayOrder[?].route ? 1 : -1))
}

const route = 'route2';

sortCustomers(customers, route);
//desired output: [{Julie}, {Betsy}, {John}]

我想使用 array.sort 但我不知道如何为传入的适当路由参数动态生成索引。

最佳答案

可以找到顺序,作为排序的值。

function sortCustomers(customers, route) {
const order = ({ displayOrder }) => displayOrder.find(o => route in o)[route];
customers.sort((a, b) => order(a) - order(b));
return customers;
}

const customers = [{ name: 'John', displayOrder: [{ route1: 1 }, { route2: 3 }] }, { name: 'Julie', displayOrder: [{ route1: 2 }, { route2: 1 }] }, { name: 'Betsy', displayOrder: [{ route1: 3 }, { route2: 2 }] }];

console.log(sortCustomers(customers, 'route2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 根据嵌套对象值对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65361564/

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