gpt4 book ai didi

javascript - 按两个最接近的字段对js数组进行排序

转载 作者:行者123 更新时间:2023-11-29 15:13:50 30 4
gpt4 key购买 nike

我想按两个字段对数组进行排序,同时提供所需的数字来对它们进行排序。我尝试使用 lodash,但没有得到想要的结果。

例如

const data = [
{name: 'first', score: 22, average: 59},
{name: 'second', score: 34, average: 83},
{name: 'third', score: 40, average: 24},
{name: 'fourth', score: 29, average: 49},
{name: 'fifth', score: 23, average: 55}
];
// call function like this
sortByTwoFields({field:'score', number:21}, {field:'average', number:50});

期望的结果是

const result = [
{name: 'fifth', score: 23, average: 55},
{name: 'fourth', score: 29, average: 49},
{name: 'first', score: 22, average: 59},
{name: 'third', score: 40, average: 24},
{name: 'second', score: 34, average: 83}
];

任何想法将不胜感激

最佳答案

简单地使用 lodash_.sortBy 怎么样?

_.sortBy(data, [a=> Math.abs(a.score - 21), a=> Math.abs(a.average - 50)])

这还不够吗?

编辑

嗯,是的!如果您需要从一个地方进行这种排序(执行)并且只有(正好是那 2 个)2 个嵌套字段,那么这个 ole liner 是可以的,但是如果您是从多个地方调用并且具有最接近值的 diff 字段(嵌套),那么您可以将其包装在一个函数中,动态准备 itarees 并将其传递给 sortBy

这是一个工作示例:

var data = [
{name: 'first', score: 22, average: 59},
{name: 'second', score: 34, average: 83},
{name: 'second', score: 34, average: 80},
{name: 'third', score: 40, average: 24},
{name: 'fourth', score: 29, average: 49},
{name: 'fifth', score: 23, average: 55}
];

function sortByClosest(arr, ...fields) {
//this will create array of callbacks, similar to what user in first example
let iteratees = fields.map(f => o => Math.abs(f.number - o[f.field]));
return _.sortBy(arr, iteratees);
}

//pass data for "arr" argument, and all other
//sort key/closest-value for fields array argument
var res = sortByClosest(data, {field:'score', number:21},{field:'average',number:50});

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

但是键,最接近的值可以以更短的格式传递,例如{score: 21, average: 50},在这种情况下生成迭代器的逻辑需要相应调整,所以会变成:

_.map(fields, (v,k)=> o=> Math.abs(v - o[k]))

并且您需要使用单个对象调用它(如上所示),这是对其的调用:

sortByClosest(数据, {score: 21, average: 50});

关于javascript - 按两个最接近的字段对js数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51519228/

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