普通數組/數組對象去重的幾種方法


一、數組去重

 

  (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退出循環
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM