Home > Article > Web Front-end > What are the three methods to remove duplicates from node arrays?
Method: 1. Use the map data structure to achieve deduplication, and store each element of the array as a key in the map; 2. Use the set method in es6 to achieve deduplication, the syntax is "Set(array) "; 3. Use the forEach statement with indexOf to achieve deduplication.
The operating environment of this article: Windows 10 system, nodejs version 12.19.0, Dell G3 computer.
The first method is to use the Map data structure to deduplicate
Create an empty Map data structure and traverse the array that needs to be deduplicated , store each element of the array as a key in the Map. Since the same key value will not appear in the Map, the final result is the deduplication result
function a(arr) { let map = new Map(); let array = new Array(); // 数组用于返回结果 for (let i = 0; i < arr.length; i++) { if (map.has(arr[i])) { // 如果有该key值 map.set(arr[i], true); } else { map.set(arr[i], false); // 如果没有该key值 array.push(arr[i]); } } return array; } var arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]; console.log(a(arr)) //[1,2,3,4,5]
The second method is to use set in ES6 which is the simplest deduplication method
let arr2 = [1, 2, 3, 4, 5, 5, 4, 3]; let res = [...new Set(arr2)]; console.log(res);
The third type forEach indexOf implements deduplication
var arr3 = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]; var b = distinct(arr3); function distinct(arr) { result = [], len = arr3.length; //len=10; arr3.forEach(function (v, i, arr3) { var bool = arr3.indexOf(v, i + 1); //从传入参数的下一个索引值开始寻找是否存在重复 if (bool === -1) { result.push(v); } }) return result; }; console.log(b.toString()); //1,2,3,4,5
Recommended learning: "nodejs video tutorial"
The above is the detailed content of What are the three methods to remove duplicates from node arrays?. For more information, please follow other related articles on the PHP Chinese website!