3
#yyds干货盘点#JS数组去重方法总结
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数组去重方法总结
原创- 双层循环判断原数组前后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
}
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
}
- ES6 set
function unique (arr) {
return Array.from(new Set(arr))
}
return Array.from(new Set(arr))
}
- indexOf 判断返回新数组
function unique (arr) {
let newArr = []
arr.forEach(item => {
if (newArr.indexOf(item) < 0) {
newArr.push(item)
}
})
return newArr
}
let newArr = []
arr.forEach(item => {
if (newArr.indexOf(item) < 0) {
newArr.push(item)
}
})
return newArr
}
- filter + indexOf
function unique (arr) {
return arr.filter((item, index, arr) => {
// console.log(arr)
// Array.filter() 的第三个入参,表示原数组
return arr.indexOf(item, 0) === index
// Array.indexOf() 的第二个入参,表示从哪个位置开始,此处没用到这个第二个参数,只是突然想起来了备注下
})
}
return arr.filter((item, index, arr) => {
// console.log(arr)
// Array.filter() 的第三个入参,表示原数组
return arr.indexOf(item, 0) === index
// Array.indexOf() 的第二个入参,表示从哪个位置开始,此处没用到这个第二个参数,只是突然想起来了备注下
})
}
- 赞
- 收藏
- 评论
- 分享
- 举报
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK