js数组去重

reduce 方案

let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myArrayWithNoDuplicates = myArray.reduce(function (previousValue, currentValue) {
  if (previousValue.indexOf(currentValue) === -1) {
    previousValue.push(currentValue)
  }
  return previousValue
}, [])

console.log(myArrayWithNoDuplicates)

es6 方案

let arrayWithNoDuplicates = Array.from(new Set(myArray))

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D

其他方案参考:https://m.php.cn/article/461751.html

posted @ 2022-08-19 17:28  蓓蕾心晴  阅读(19)  评论(0编辑  收藏  举报