数组去除重复值的四种超简便⽅法⽅式⼀:使⽤filter()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
// item:当前项,index:当前索引,arr:当前数组
arr1.filter((item, index, arr) => {
if (arr.indexOf(item) === index) {
arr2.push(item)
}
})
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
⽅式⼆:使⽤includes()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
arr1.forEach(item => {
if (!arr2.includes(item)) {
arr2.push(item)
}
})
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
⽅式三:使⽤indexOf()
字段字符串去重复let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
arr1.forEach(item => {
if (arr2.indexOf(item) < 0) {
arr2.push(item)
}
})
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
⽅式四:使⽤es6的Set()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
// Set()去⾃动去除重复项
arr2 = [...new Set(arr1)]
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论