普通数组/数组对象去重的几种方法

一、数组去重

  (1)ES5方法! 利用 filter 和 indexOF方法

复制代码
 
 
let arr = [1, 1, 2, 3, undefined, null, null, 23, 'g', 'g']
function uniq (array){
 return [].filter.call(array, function (item, index) { 
    return array.indexOf(item) == index 
    })
}

console.log(uniq(arr)) // [1, 2, 3, undefined, null, 23, "g"]
复制代码

  

  (2)ES6方法! 利用 new Set()方法配合ES6 展开运算符: Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用

let arr = [1, 1, 2, 3, undefined, null, null, 23, 'g', 'g']
console.log([...new Set(arr)]) // [1, 2, 3, undefined, null, 23, "g"]

  (3)ES6方法! 利用 reduce

   

复制代码
(1)对普通数组去重
let arr = arr = [1, 2 , 2, ,3, 2 ,4 ,1, 1, 1, 2]

let newArr = arr.reduce(function (item, next) {
    obj[next] ? '' : obj[next] = true && item.push(next)
    return item
}, [])
console.log(newArr) // [1, 2, 3, 4]

(2)数组对象去重

let arr2 = [
    {id: 1},
    {id: 1},
    {id: 1},
    {id: 2},
    {id: 4},
]
let newArr2 = arr.reduce(function (item, next) {
    console.log(item)
    obj[next.id] ? '' : obj[next.id] = true && item.push(next)
    return item
}, [])
console.log(newArr2)
复制代码

二、数组某项第一个查找

  find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(item => item > 10);

console.log(found); // 12

三、数组遍历,可中断和不可中断 循环

  除了简单的 for , do...while 循环外,还有 forEach,map

   for 可以用 break 跳出循环遍历外,forEach,map 不能跳出遍历,

复制代码
let arr = [1, 1, 2, 3, undefined, null, null, 23, "g", "g"]

for (let i = 0, len = arr.length; i < arr.len; i++) {
    console.log(i) // 0, 1, 2, 3
    if (i === 3) {
        break // 注意仅可用 break退出循环
    }
}

猜你喜欢

转载自www.cnblogs.com/lgnblog/p/12518320.html