gpt4 book ai didi

javascript - 减少对象数组: limit similar fields based on value from another field

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:45 25 4
gpt4 key购买 nike

我需要一种快速的方法来执行此操作。它必须要快。

在数组中,对象已按分数排序。我想用任何给定 rootTerm 的前 2 个得分对象创建一个新数组。

这是原文。

"results": [
{
"score": 100,
"source": {
"term": "bovine1",
"rootTerm": "cow",
}
},
{
"score": 50,
"source": {
"term": "bovine2",
"rootTerm": "cow",
}
},
{
"score": 10,
"source": {
"term": "bovine3",
"rootTerm": "cow",
}
},
{
"score": 10,
"source": {
"term": "scrofa",
"rootTerm": "pig",
}
]

Bovine3 不在 rootTerm 牛得分最高的前 2 个对象中,因此我希望将其删除。

新的结果将是

"results": [
{
"score": 100,
"source": {
"term": "bovine1",
"rootTerm": "cow",
}
},
{
"score": 50,
"source": {
"term": "bovine2",
"rootTerm": "cow",
}
},
{
"score": 10,
"source": {
"term": "scrofa",
"rootTerm": "pig",
}
]

最佳答案

您可以使用Array.filter()对其进行过滤,但您确实需要在看到根术语时对其进行跟踪,并在进行过程中保持计数。

var tracker = {};
data.filter(function(value, index, array) {
var rootTerm = value.source.rootTerm;
if (undefined === tracker[rootTerm])
{
tracker[rootTerm] = 0;
}
tracker[rootTerm] += 1;
return (tracker[rootTerm] <= 2)
});

关于javascript - 减少对象数组: limit similar fields based on value from another field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231276/

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