gpt4 book ai didi

javascript - 使用 lodash 将对象数组排序为 Top N,其中 n+1 为 "others"

转载 作者:行者123 更新时间:2023-11-29 14:47:41 27 4
gpt4 key购买 nike

假设我有这个数据结构,示例输入:

[ {name: "a", val:1},
{name: "b", val:2},
{name: "c", val:3},
{name: "d", val:4},
{name: "e", val:5},
{name: "f", val:1},
{name: "g", val:2},
{name: "h", val:1},
]

我想输出 2 个数组:

首先是对象的 val 属性,首先是最高(最高)值,然后是剩余元素的总和。如果我们假设 n=5,作为前 5 个结果 +“其余”。所以 array[5] 上的这个数组 = 所有不在前 5 名中的 val 属性的总和。示例输出:

[2,3,4,5,2,3]

第二个数组将是与前 5 个对应的名称属性,其中 array[5] = "others",或其他一些任意字符串。示例输出:

["b","c","d","e","g","others"]

如何使用 lodash 以最大效率和/或最大代码清晰度来实现这一点? lodash

编辑:示例代码:

       var n = 5;
var input = [
{name: "a", val:1},
{name: "b", val:2},
{name: "c", val:3},
{name: "d", val:4},
{name: "e", val:5},
{name: "f", val:1},
{name: "g", val:2},
{name: "h", val:1},
];
var sortedArray = _.sortByOrder(input, ['val'], [false]);
var topNValues = _.pluck(_.slice(sortedArray, 0, n), 'val');
var restValues = _.pluck(_.slice(sortedArray, n, sortedArray.length), 'val');
var restAdded = _.reduce(restValues, function(i, j) {
return i + j;
}, 0);
topNValues.splice(n, 0,restAdded);
$scope.array1 = topNValues;
var names = _.pluck(_.slice(sortedArray, 0, n), 'name');
names.splice(n,0,"others");
$scope.array2 = names;

一定有比我的 jsfiddle 更干净的链接方式:http://jsfiddle.net/u1w4da6r/2/

最佳答案

所以它不是单链,但看起来相当容易阅读。我没有进行任何性能测试,但易于理解可能应该是您的主要目标。

Codepen

function groupOthers (obj, n) {
var indicesToKeep = _.chain(obj)
.map(function (item, index) { //zip each item with its index
return {item: item, index: index}
})
.sortBy(function (zipped) { //sort by the val (highest to lowest)
return -zipped.item.val
})
.take(n) //take the top 5
.map('index') // we only care about the indices
.value()

var partitioned = _.partition(obj, function (item, index) {
return _.includes(indicesToKeep, index)
})

var finalObjJoined = partitioned[0].concat({
name: 'others',
val: _.sum(partitioned[1], 'val')
})

return [_.map(finalObjJoined, 'name'), _.map(finalObjJoined, 'val')]
}

console.log(groupOthers(x, 5))

关于javascript - 使用 lodash 将对象数组排序为 Top N,其中 n+1 为 "others",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623441/

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