首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >js数组去重

js数组去重

作者头像
蓓蕾心晴
发布于 2022-08-20 13:02:39
发布于 2022-08-20 13:02:39
3.5K0
举报
文章被收录于专栏:前端小叙前端小叙

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#%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-08-19,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档