数组去重:
- Set 结构不会添加重复的值。
Array.from
把 Set 结构转换为数组 map.has(property)
判断属性是否存在 ,map的键不会转换为字符串Array.includes(value)
判断值是否存在于数组中- 遍历两次,使用
===
全等运算符判断是否相等 - 使用 filter 过滤数组,hasOwnProperty 判断对象是否存在某属性,将数据类型和数据作为对象的属性,如果存在相同的就返回false,表示过滤。
let originalArray = [1,2,3,4,5,3,2,4,1];
// 方式1 Set
const result = Array.from(new Set(originalArray));
console.log(result); // -> [1, 2, 3, 4, 5]
// 方式2
const result = [];
const map = new Map();
for (let v of originalArray) {
if (!map.has(v)) {
map.set(v, true);
result.push(v);
}
}
console.log(result); // -> [1, 2, 3, 4, 5]
// 方式3
const result = [];
for (let v of originalArray) {
if (!result.includes(v)) {
result.push(v);
}
}
console.log(result); // -> [1, 2, 3, 4, 5]
// 方式4
for (let i = 0; i < originalArray.length; i++) {
for (let j = i + 1; j < originalArray.length; j++) {
if (originalArray[i] === originalArray[j]) {
originalArray.splice(j, 1);
j--;
}
}
}
console.log(originalArray); // -> [1, 2, 3, 4, 5]
// 方式5
const obj = {};
const result = originalArray.filter(item => obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true));
console.log(result); // -> [1, 2, 3, 4, 5]
对象数组去重:
reduce 用法
语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
const responseList = [
{ id: 1, a: 1 },
{ id: 2, a: 2 },
{ id: 3, a: 3 },
{ id: 1, a: 4 },
];
const result = responseList.reduce((acc, cur) => {
//map用于返回符合表达式的数据
const ids = acc.map(item => item.id);
// ...运算符用于将数组拆成,分隔的字符串
return ids.includes(cur.id) ? acc : [...acc, cur];
}, []);
console.log(result); // -> [ { id: 1, a: 1}, {id: 2, a: 2}, {id: 3, a: 3} ]