js数组去重的几种方式

一、数组对象去重

情况一:数组对象的属性都相同

1.使用map()得到一个由JSON.stringify处理后的字符串数组。
2.new Set()将字符串数组去重。
3.使用Array.from()构建得到一个由处理后的对象数组。

const array = [
  { id: 12, name: '小肖' },
  { id: 13, name: '小花' },
  { id: 12, name: '小肖' }
]

// 去重
const result = Array.from(new Set(array.map(JSON.stringify)), JSON.parse);

情况二:数组对象的某一个属性相同

const array = [
  { id: 12, name: '小肖' },
  { id: 13, name: '小花' },
  { id: 12, name: '小丽' }
]

// 去重
const result = Array.from(new Map(array.map(item => [item.id, item])).values());

二、字符串数组或数字数组

const strArray = ['abc', 'bca', 'cab', 'abc']
// new Set() 得到的是一个Set对象,所有需要[...set]或Array.from(set)转为数组形式
const result = [...new Set(strArray)]
console.log(result); // ['abc', 'bca', 'cab']

数字数组同理

const numberArray = [1, 2, 3, 2, 1]
const result = [...new Set(numberArray)]
console.log(result); // [1, 2, 3]