js数组去重是面试中经常会碰到的问题,无论是前端还是node。js数组常见的有两种形式,一种是数组各元素均为基本数据类型,常见的为数组字符串格式,形如['a','b','c'];一种是数组各元素不定,元素中既有基本数据类型,也有引用数据类型,形式如[{name:1,age:2}];这里介绍两种常见的js去重方式.
方法一:针对数组字符串形式(利用set)
let arr = [1,2,3,4,5,4,3,2,1];
let set = new Set();
arr.forEach((item)=> set.add(item));
let a = Array.from(set);
console.log(a);
方法二: 针对数组元素类型不定情况下,通常是数组内包裹对象(利用对象的key唯一特效);
let arr = [
{ name:'zhangsan', age: 22, },
{ name:'zhangsan', age: 22, },
{ name:'lisi', age: 23, }
];
let obj = {};
arr.forEach((item)=> obj[item.name]=item);
let a = [];
for ( let key in obj) { a.push(obj[key])};
console.log(a);
转载自: https://www.sixstone.top