for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1) // 因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
j--
}
}
补充
如果要比较对象中的值是否相等,可以使用 lodash/isEqual
方法,可以比较对象嵌套深层的内容
import isEqual from 'lodash/isEqual'
let object = { a: 1, c: { d: 1 } }
let other = { a: 1, c: { d: 1 } }
isEqual(object, other)
// => true
数组对象去重
import { isEqual, uniqWith, uniqBy } from 'lodash'
let arr = [
{id: 1, name: 'xx', year: 18},
{id: 2, name: 'xxx', year: 19},
{id: 1, name: 'xxx', year: 20},
{id: 3, name: 'xx', year: 21},
{id: 3, name: 'xx', year: 18},
]
console.log('原数组:', arr);
console.log('根据id去掉相同的元素:', uniqBy(arr, 'id'));
console.log('检查数组每一项进行去重:', uniqWith(arr, isEqual));
数组去重
在JavaScript中,有多种方法可以对数组进行去重。以下是几种常用的方法:
使用Se
t:Set
是ES6中引入的新的数据结构,它可以存储唯一的值。通过将数组转换为Set
,然后再将Set
转换回数组,就可以实现去重。
const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = Array.from(new Set(arr));
console.log(uniqueArr); // [1, 2, 3, 4, 5]
使用filter
方法和indexOf
:遍历数组,通过判断元素在数组中的索引位置,来去掉重复的元素。
const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.filter((item, index) => {
return arr.indexOf(item) === index;
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]
使用reduce
方法:遍历数组,将元素添加到一个新数组中,在添加之前检查新数组中是否已存在相同的元素。
const arr = [1, 2, 3, 3, 4, 4, 5];
const uniqueArr = arr.reduce((acc, curr) => {
if (!acc.includes(curr)) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]
使用Map
:遍历数组,将元素作为Map的键,判断键是否存在于Ma
p中,如果不存在则添加到新数组中。
const arr = [1, 2, 3, 3, 4, 4, 5];
const map = new Map();
const uniqueArr = [];
arr.forEach(item => {
if (!map.has(item)) {
map.set(item, true);
uniqueArr.push(item);
}
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]