3

#yyds干货盘点#JS数组去重方法总结

 1 year ago
source link: https://blog.51cto.com/u_11365839/5432147
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点#JS数组去重方法总结

原创

尼羲 2022-06-30 17:22:14 博主文章分类:技术扯淡 ©著作权

文章标签 数组 i++ 文章分类 JavaScript 前端开发 yyds干货盘点 阅读数115

  1. 双层循环判断原数组前后item是否重复
function unique (arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1)
}
}
}
return arr
}
  1. ES6 set
function unique (arr) {
return Array.from(new Set(arr))
}
  1. indexOf 判断返回新数组
function unique (arr) {
let newArr = []
arr.forEach(item => {
if (newArr.indexOf(item) < 0) {
newArr.push(item)
}
})
return newArr
}
  1. ​filter + indexOf
function unique (arr) {
return arr.filter((item, index, arr) => {
// console.log(arr)
// Array.filter() 的第三个入参,表示原数组
return arr.indexOf(item, 0) === index
// Array.indexOf() 的第二个入参,表示从哪个位置开始,此处没用到这个第二个参数,只是突然想起来了备注下
})
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK