JS小技巧,如何去重对象数组?(JavaScript实用技巧:轻松去除对象数组中的重复项)
原创
一、引言
在JavaScript开发过程中,我们常常需要处理对象数组,而对象数组的去重是一个常见的需求。本文将介绍几种实用的方法,帮助开发者轻松去除对象数组中的重复项。
二、对象数组去重原理
对象数组去重,重点是指去除数组中重复的对象。这里的“重复”通常是指对象的某些属性值相同。例如,以下数组中的两个对象,由于它们的“name”和“age”属性值相同,于是被认为是重复的:
[
{name: '张三', age: 25},
{name: '李四', age: 30},
{name: '张三', age: 25}
]
去重后,该数组应仅包含以下对象:
[
{name: '张三', age: 25},
{name: '李四', age: 30}
]
三、去重方法一:利用数组原生的filter方法
使用数组的filter方法,可以实现对对象数组的去重。以下是一个明了的示例:
function uniqueArray(array, key) {
const result = array.filter((item, index, arr) => {
return arr.findIndex(t => t[key] === item[key]) === index;
});
return result;
}
const array = [
{name: '张三', age: 25},
{name: '李四', age: 30},
{name: '张三', age: 25}
];
const uniqueArrayResult = uniqueArray(array, 'name');
console.log(uniqueArrayResult);
在这个示例中,我们定义了一个uniqueArray函数,它接受两个参数:对象数组和需要比较的键。通过filter方法和findIndex方法,我们可以找到具有相同键值的第一个对象,并将其余具有相同键值的对象过滤掉。
四、去重方法二:利用Map对象
Map对象是ES6中新增的数据结构,它具有很好的查找性能。我们可以使用Map对象来实现对象数组的去重。以下是一个示例:
function uniqueArrayWithMap(array, key) {
const map = new Map();
const result = [];
for (const item of array) {
if (!map.has(item[key])) {
map.set(item[key], true);
result.push(item);
}
}
return result;
}
const array = [
{name: '张三', age: 25},
{name: '李四', age: 30},
{name: '张三', age: 25}
];
const uniqueArrayWithMapResult = uniqueArrayWithMap(array, 'name');
console.log(uniqueArrayWithMapResult);
在这个示例中,我们定义了一个uniqueArrayWithMap函数,它使用Map对象来存储已经出现过的键值。如果Map中不存在某个键值,则将其添加到Map中,并将对应的对象添加到导致数组中。
五、去重方法三:利用reduce方法
reduce方法是数组的一个高阶函数,它可以对数组的每个元素执行一个累加器函数,将其导致汇总为单个返回值。我们可以使用reduce方法来实现对象数组的去重。以下是一个示例:
function uniqueArrayWithReduce(array, key) {
return array.reduce((prev, cur) => {
if (!prev.find(item => item[key] === cur[key])) {
prev.push(cur);
}
return prev;
}, []);
}
const array = [
{name: '张三', age: 25},
{name: '李四', age: 30},
{name: '张三', age: 25}
];
const uniqueArrayWithReduceResult = uniqueArrayWithReduce(array, 'name');
console.log(uniqueArrayWithReduceResult);
在这个示例中,我们定义了一个uniqueArrayWithReduce函数,它使用reduce方法遍历数组,并通过find方法检查累加器数组中是否已经存在具有相同键值的对象。如果不存在,则将其添加到累加器数组中。
六、去重方法四:利用JSON字符串化
将对象演化为JSON字符串是一种明了的方法,但这种方法并不完美,出于它无法处理具有嵌套对象或数组的情况。以下是一个示例:
function uniqueArrayWithJSON(array) {
const uniqueArray = [];
const jsonSet = new Set();
array.forEach(item => {
const jsonString = JSON.stringify(item);
if (!jsonSet.has(jsonString)) {
jsonSet.add(jsonString);
uniqueArray.push(item);
}
});
return uniqueArray;
}
const array = [
{name: '张三', age: 25},
{name: '李四', age: 30},
{name: '张三', age: 25}
];
const uniqueArrayWithJSONResult = uniqueArrayWithJSON(array);
console.log(uniqueArrayWithJSONResult);
在这个示例中,我们定义了一个uniqueArrayWithJSON函数,它使用JSON.stringify方法将对象演化为字符串,并使用Set对象来存储已经出现过的字符串。如果Set中不存在某个字符串,则将其添加到Set中,并将对应的对象添加到导致数组中。
七、总结
本文介绍了四种实用的对象数组去重方法,分别是利用filter方法、Map对象、reduce方法和JSON字符串化。每种方法都有其优缺点,开发者可以凭借实际需求选择合适的方法。在实际开发中,我们还需要注意对象数组去重时的性能问题,特别是在处理大量数据时,应该选择高效能更高的方法。