美文网首页
js数组去重

js数组去重

作者: honglingdai | 来源:发表于2018-03-22 10:10 被阅读0次

方法一 (es6 set方法,简单粗暴)

function unique(arr) {
  return Array.from(new Set(arr))
}
console.log(unique([1,3,4,5,6,4,4,23,5,'a','c','a']))

方法二 创建空数组,用indexOf方法检索,没有的话插入新数组中

function unique1(arr) {
  let newArr = []
  arr.forEach(item => {
    if(newArr.indexOf(item) === -1){
      newArr.push(item)
    }
  })
  return newArr
}
console.log(unique1([1,3,4,5,6,4,4,23,5,'a','c','a']))

方法三 下标判断,思路跟上面大致相同

    function unique2(arr) {
        let newArr = []
        arr.forEach((item,index) => {
            if(arr.indexOf(item) === index){    //如果数组元素的下标的等于 index,存入新的数组
              newArr.push(item)
            }
        })
        return newArr
    }
    console.log(unique2([1,3,4,5,6,4,4,23,5,'a','c','a']))

相关文章

  • 数组的去重和数组中对象的去重

    数组中对象去重 方式1 jq方式 方式2 原生js方式 普通数组的去重 方式1 普通的数组去重js 方式2 Se...

  • js数组去重、对象数组去重

    普通数组去重 一、普通数组去重 方法一:遍历数组法 方法二:排序法 方法三:对象法 对象数组去重 方法一:将对象数...

  • js数组去重

    Set结构去重 ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。 向 Se...

  • JS数组去重

    方法1:两层for循环,外层循环原数组,内层循环时进行比较。 方法2:利用对象的属性不能相同的特点去重 方法3:利...

  • js数组去重

  • js数组去重

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

  • js数组去重

  • js 数组去重

  • JS数组去重

    方法一:遍历数组,建立新数组,利用indexOf判断是否存在于新数组中,不存在则push到新数组,最后返回新数组 ...

  • js数组去重

    方法一 (es6 set方法,简单粗暴) 方法二 创建空数组,用indexOf方法检索,没有的话插入新数组中 方...

网友评论

      本文标题:js数组去重

      本文链接:https://www.haomeiwen.com/subject/qlvoqftx.html