js数组去重

1.利用对象的属性唯一性去重

//利用对象的属性值唯一性去重
function unique(array) {
  let obj = {}
  let result = []
  //es6引入的for...of默认调用数组的values迭代器,故item为数组每一项的值
  //es5的for...in循环出的是key,即item是数组的索引(String类型)
  for(let item of array) {
    if(!obj[item]) {
      obj[item] = 1;
      result.push(item)
    }
  }
  return result
}

2.利用es6的Set

//利用es6的Set
function unique(array) {
  /**
  * Set是es6新类型,是一种无重复值的有序列表
  * Set、Map、数组都是js的集合类型
  * 可使用Array.from()或...扩展运算符来生成数组
  */
  return Array.from(new Set(array))
  // 或者如下:
  // return [...(new Set(array))]
}

你可能感兴趣的:(js数组去重)