当前位置:网站首页>Summary of array de duplication methods in JS

Summary of array de duplication methods in JS

2020-11-10 17:46:28 Xingyu, constant struggle, passer-by

1. Suppose the state variable , The outer layer traverses the array , Inside the array traversal is traversing through , Comparison of the new array with the original array , Carry out the operation of taking weight

Code :

var oldArr = ['a', 'b', 121, 22, 88, 88, 22,22,1111,0,99]
var newArr = []
for (let i = 0; i < oldArr.length; i++) {
var bl = true
for (let j = 0; j < newArr.length; j++) {
if (oldArr[i] === newArr[j]) {
bl = false
break
}
}
if (bl) {
newArr.push(oldArr[i])
}
}
console.log(newArr) // ["a", "b", 121, 22, 88, 1111, 0, 99]

2. utilize indexOf Method , To retrieve values that are not duplicated in a new array , No return -1, Push non duplicate values into the new array

Code :

var oldArr = ['a','a','b', 121, 22, 88, 88, 22,22,1111,0,99]
var newArr = []
for(let i=0;i<oldArr.length;i++){
if(newArr.indexOf(oldArr[i])===-1){
newArr.push(oldArr[i]);
}
}
console.log(newArr);//["a", "b", 121, 22, 88, 1111, 0, 99]

3.

版权声明
本文为[Xingyu, constant struggle, passer-by]所创,转载请带上原文链接,感谢