- 使用 Set(ES6):
const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(originalArray)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
- 使用 filter() 方法:
const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = originalArray.filter((item, index) => originalArray.indexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
- 使用 reduce() 方法:
const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = originalArray.reduce((acc, current) => {
if (!acc.includes(current)) {
acc.push(current);
}
return acc;
}, []);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
- 使用 forEach() 方法:
const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [];
originalArray.forEach(item => {
if (!uniqueArray.includes(item)) {
uniqueArray.push(item);
}
});
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
- 使用 Object 键值对:
const originalArray = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = Array.from(new Set(originalArray));
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
对象数组去重方法:
1、使用 Set(ES6):
const originalArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Alice' },
{ id: 1, name: 'John' }, // 重复的对象
{ id: 3, name: 'Bob' },
// ...
];
// 使用 Set 和 JSON.stringify 将对象转换成字符串进行去重
const uniqueSet = new Set(originalArray.map(obj => JSON.stringify(obj)));
// 将 Set 转换回对象数组
const uniqueArray = Array.from(uniqueSet).map(str => JSON.parse(str));
console.log(uniqueArray);
// Output: [
// { id: 1, name: 'John' },
// { id: 2, name: 'Alice' },
// { id: 3, name: 'Bob' }
// ]
2、使用 lodash 的 uniqBy() 方法:
const originalArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Alice' },
{ id: 1, name: 'John' }, // 重复的对象
{ id: 3, name: 'Bob' },
// ...
];
// 使用 lodash 的 uniqBy() 方法,根据 id 属性进行去重
const _ = require('lodash');
const uniqueArray = _.uniqBy(originalArray, 'id');
console.log(uniqueArray);
// Output: [
// { id: 1, name: 'John' },
// { id: 2, name: 'Alice' },
// { id: 3, name: 'Bob' }
// ]
3、使用 reduce() 方法:
const originalArray = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Alice' },
{ id: 1, name: 'John' }, // 重复的对象
{ id: 3, name: 'Bob' },
// ...
];
// 使用 reduce() 方法,根据 id 属性进行去重
const uniqueArray = originalArray.reduce((acc, obj) => {
if (!acc.some(item => item.id === obj.id)) {
acc.push(obj);
}
return acc;
}, []);
console.log(uniqueArray);
// Output: [
// { id: 1, name: 'John' },
// { id: 2, name: 'Alice' },
// { id: 3, name: 'Bob' }
// ]