js数组去重

2022-08-20 13:02:39 浏览数 (1)

reduce 方案

代码语言:javascript复制
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 方案

代码语言:javascript复制
let arrayWithNoDuplicates = Array.from(new Set(myArray))

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#数组去重

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

0 人点赞