zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js数组去重

2023-06-13 09:11:17 时间

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