gpt4 book ai didi

javascript - 如何从 JavaScript 中的对象数组中获取重复值?

转载 作者:行者123 更新时间:2023-11-28 12:15:16 25 4
gpt4 key购买 nike

我的问题是我需要过滤一组数据...

我的数据携带..

var arrayWithDuplicates = [
{"licenseNum": "6", "state":"NV"},
{"licenseNum": "6", "state":"NV"},
{"licenseNum": "6", "state":"NV"},
{"licenseNum": "6", "state":"CA"},
{"licenseNum": "6", "state":"CA"},
{"licenseNum": "6", "state":"OR"},
{"licenseNum": "6", "state":"OR"},
{"licenseNum": "6", "state":"OR"},
{"licenseNum": "20", "state":"NV"},
{"licenseNum": "10", "state":"CA"},
{"licenseNum": "10", "state":"NV"},
{"licenseNum": "10", "state":"OR"},
{"licenseNum": "10", "state":"CA"}
];

新数据应该是

newdata = [6, 6, 6, 20, 10, 10, 10];

我已经尝试过..

for (i = 0; i < arrayWithDuplicates .length; i++) {
if ((arrayWithDuplicates[i].licenseNum) === -1)) {
newdata .push({
licenseNum: arrayWithDuplicates[i].licenseNum,
state: arrayWithDuplicates[i].state
});
}
};

从这些结果中,我得到了..

newdata = [6, 20, 10]

我已经看过很多很好的例子,但它仍然不能解决我的问题。非常感谢。

最佳答案

获取独特的条目并筛选出您需要的内容。查找下面的内联评论以查看该方法

var arrayWithDuplicates = [
{"licenseNum": "6", state:"NV"},
{"licenseNum": "6", state:"CA"},
{"licenseNum": "6", state:"OR"},
{"licenseNum": "6", state:"OR"},
{"licenseNum": "6", state:"OR"},
{"licenseNum": "20", state:"NV"},
{"licenseNum": "10", state:"CA"},
{"licenseNum": "10", state:"CA"},
{"licenseNum": "10", state:"OR"},
{"licenseNum": "10", state:"CA"}
];

json = arrayWithDuplicates.map(x => JSON.stringify(x)) // maps each array entry in stringified json, so I could get unique entries below

var result = json.filter(function(item, pos) {
return json.indexOf(item) == pos; // gives unique entries
}).map(x => +JSON.parse(x).licenseNum) // parses back json and gives licenseNum
console.log(result)
// [6, 6, 6, 20, 10, 10]

关于javascript - 如何从 JavaScript 中的对象数组中获取重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992925/

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