gpt4 book ai didi

javascript - 如何使用 AngularJS 获取具有唯一值的数组

转载 作者:行者123 更新时间:2023-11-30 07:58:08 24 4
gpt4 key购买 nike

我有一个包含重复项的数组。如何获得包含唯一项的数组?

a= [{id: "1", campus: "c1"}, {id: "1", campus: "c1"}, {id: "2", campus: "c2"}, {id: "2", campus: "c2"}]

我想要具有独特对象的结果

a= [{id: "1", campus: "c1"}, {id: "2", campus: "c2"}]

最佳答案

您可以使用 Array#filter如下:

var arr = [{
id: "1",
campus: "c1"
}, {
id: "1",
campus: "c1"
}, {
id: "2",
campus: "c2"
}, {
id: "2",
campus: "c2"
}];

// Keep an array of elements whose id is added in filtered array
var elementId = [];

var newArr = arr.filter(el => {
if (elementId.indexOf(el.id) === -1) {
// If not present in array, then add it
elementId.push(el.id);
return true;
} else {
// Already present in array, don't add it
return false;
}
});

console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<pre id="result"></pre>


基于 OP 的 comment

Please suggest best way with respect to performance..

如果您可以使用下划线/lodash

您可以使用 _.uniqWith

_.uniqWith(arr, _.isEqual);

var arr = [{
id: "1",
campus: "c1"
}, {
id: "1",
campus: "c1"
}, {
id: "2",
campus: "c2"
}, {
id: "2",
campus: "c2"
}];

var newArr = _.uniqWith(arr, _.isEqual);
console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js"></script>
<pre id="result"></pre>

您还可以使用 _.uniqBy

_.uniqBy(arr, 'id');

var arr = [{
id: "1",
campus: "c1"
}, {
id: "1",
campus: "c1"
}, {
id: "2",
campus: "c2"
}, {
id: "2",
campus: "c2"
}];

var newArr = _.uniqBy(arr, 'id');
console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js"></script>
<pre id="result"></pre>

关于javascript - 如何使用 AngularJS 获取具有唯一值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34990611/

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