gpt4 book ai didi

javascript - 如何使用下划线选择最大的数组元素

转载 作者:行者123 更新时间:2023-11-28 18:51:45 25 4
gpt4 key购买 nike

我有以下数组:

var array = [[{key1: 1, key2: thing}, {key1: 3, key2: thing}],
[{key1: 4, key2: stuff}, {key1: 2, key2: stuff}],
[{key1: 3, key2: onlyOne}]]

我需要取出少于两个对象的任何数组,并且每个可能包含“n”个对象的剩余数组应该只包含具有最小 key1 的对象。最后我会:

var updatedArray = [[{key1: 1, key2: thing}],[{key1: 2, key2: stuff}]]

如何使用 Underscore 来获取此内容?

现在我已经完成了:

var soFar = _.filter(_.groupBy(_.map(array, function(n){return _.find(n)}), 
"key2"), function(n){return n.length > 1});

//soFar = [[{key1: 1, key2: thing}, {key1: 3, key2: thing}],
//[{key1: 4, key2: stuff}, {key1: 2, key2: stuff}]]`

这让我摆脱了只有一个对象的数组,但我无法根据对象的比较找出下一部分来修改每个数组。

最佳答案

这是按照OP要求使用undersore/lodash的答案:

var array = [
[{
key1: 1,
key2: 'thing'
}, {
key1: 3,
key2: 'thing'
}],
[{
key1: 4,
key2: 'stuff'
}, {
key1: 2,
key2: 'stuff'
}],
[{
key1: 3,
key2: 'onlyOne'
}]
];

array = _.filter(array, function(v) {
return v.length >= 2;
});

array = _.map(array, function(v) {
v.sort(function(a, b) {
return a.key1 > b.key1;
});
return [v[0]];
});


console.log(array);

第二种方法,我们将映射和过滤函数合并到一个语句中。接下来还有一点困惑。

var array = [
[{
key1: 1,
key2: 'thing'
}, {
key1: 3,
key2: 'thing'
}],
[{
key1: 4,
key2: 'stuff'
}, {
key1: 2,
key2: 'stuff'
}],
[{
key1: 3,
key2: 'onlyOne'
}]
];

array = _.map(_.filter(array, function(v) {
return v.length >= 2;
}), function(v) {
v.sort(function(a, b) {
return a.key1 > b.key1;
});
return [v[0]];
});


console.log(array);

输出:

enter image description here

关于javascript - 如何使用下划线选择最大的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34409924/

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