JavaScript 数组去重:使用 filter 和 findIndex 方法去除重复 ID 的元素
JavaScript 数组去重:使用 filter 和 findIndex 方法去除重复 ID 的元素
在 JavaScript 中,你可以使用 Array.filter() 方法和 Array.findIndex() 方法来去除数组中具有相同 ID 的元素。
示例代码
let a = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'Mike' },
{ id: 3, name: 'Alice' }
];
let uniqueArray = a.filter((item, index, arr) => {
return arr.findIndex(obj => obj.id === item.id) === index;
});
console.log(uniqueArray);
解释
Array.filter()方法用于遍历数组a,并根据条件筛选出符合要求的元素。Array.findIndex()方法用于在数组中查找第一个满足条件的元素,并返回其索引。- 在
filter()方法的回调函数中,我们使用findIndex()方法查找与当前元素item具有相同id的元素,并比较其索引与当前元素的索引。 - 如果两个索引相同,则说明当前元素是唯一的,将其保留在结果数组
uniqueArray中。
输出结果
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Alice' }
]
通过以上代码,我们成功地从数组 a 中去除了重复 ID 的元素,得到一个包含唯一 ID 元素的新数组 uniqueArray。
原文地址: https://www.cveoy.top/t/topic/nkZv 著作权归作者所有。请勿转载和采集!