数组去重
普通类型数组去重
- 使用Set数据结构: Set是一种特殊的数据结构,它不会存储重复的值。我们可以通过将数组转换为Set,然后再将Set转换回数组来去除数组中的重复元素。
js
let array = [1, 2, 2, 3, 4, 4, 5];
let uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出:[1, 2, 3, 4, 5]- 使用filter方法: filter方法会创建一个新数组,该新数组包含所有通过测试的元素。我们可以通过检查数组中是否已经存在当前元素来去除重复元素。
js
let array = [1, 2, 2, 3, 4, 4, 5];
let uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray); // 输出:[1, 2, 3, 4, 5]- 使用reduce方法: reduce方法可以将数组中的所有元素减少到一个单一的值。我们可以通过将数组转换为一个对象,然后再将对象的值转换回数组来去除重复元素。
js
let array = [1, 2, 2, 3, 4, 4, 5];
let uniqueArray = Object.values(array.reduce((acc, value) => {
acc[value] = value;
return acc;
}, {}));
console.log(uniqueArray); // 输出:[1, 2, 3, 4, 5]对象类型数组去重
- 使用Set数据结构: Set是一种特殊的数据结构,它不会存储重复的值。我们可以通过将对象数组转换为Set,然后再将Set转换回数组来去除对象数组中的重复元素。
js
let array = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
let uniqueArray = [...new Set(array.map(JSON.stringify))].map(JSON.parse);
console.log(uniqueArray); // 输出:[{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]- 使用filter方法: filter方法会创建一个新数组,该新数组包含所有通过测试的元素。我们可以通过检查数组中是否已经存在当前元素来去除重复元素。
js
let array = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
let uniqueArray = array.filter((value, index, self) => {
return index === self.findIndex(t => JSON.stringify(t) === JSON.stringify(value));
});
console.log(uniqueArray); // 输出:[{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]- 使用reduce方法: reduce方法可以将数组中的所有元素减少到一个单一的值。我们可以通过将对象数组转换为一个对象,然后再将对象的值转换回数组来去除重复元素。
js
let array = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
let uniqueArray = Object.values(array.reduce((acc, value) => {
acc[JSON.stringify(value)] = value;
return acc;
}, {}));
console.log(uniqueArray); // 输出:[{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, {id: 3, name: 'Charlie'}]