Briefly describe the Js array deduplication method

1. You can use the Set data structure of ES6 to remove duplicate elements in the array, the code is as follows:

var arr = [1,2,3,4,5,1,2,3];

var newArr = [...new Set(arr)];

console.log(newArr); // [1,2,3,4,5]

2. You can use the Array.prototype.filter() method to remove duplicate elements in the array. The code is as follows:

var arr = [1,2,3,4,5,1,2,3];

var newArr = arr.filter(function(item, index, arr){

return arr.indexOf(item) === index;

});

console.log(newArr); // [1,2,3,4,5]

3. You can use the Array.prototype.reduce() method to remove repeated elements in the array. The code is as follows:

var arr = [1,2,3,4,5,1,2,3];

var newArr = arr.reduce(function(prev, cur){

if(prev.indexOf(cur) === -1){

prev.push(cur);

} return prev;

}, []);

console.log(newArr); // [1,2,3,4,5]

4. You can use the Array.prototype.forEach() method to remove repeated elements in the array, the code is as follows:

var arr = [1,2,3,4,5,1,2,3];

var newArr = [];

arr.forEach(function(item){

if(newArr.indexOf(item) === -1){

newArr.push(item);

}});

console.log(newArr); // [1,2,3,4,5]

Guess you like

Origin blog.csdn.net/JohnJill/article/details/129220471