The content of this article is about how to implement array deduplication and repeated element statistics in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Deduplication
This uses the feature of ES6 Set structure that does not allow data duplication
let arr1 = [1,1,2,3,1,2,4,2]; //先将数组转化为Set数据类型,然后再转回数组类型 let dedupeArr = Array.from(new Set(arr1));
2. Statistics
let count = 0; let obj = {}; //最终返回的数据 dedupeArr.forEach(i=>{ count = 0; arr1.forEach(j=>{ if(i===j) count++; }) obj[i] = count;//键名为i(数组元素),值为count(出现次数) })
3. Traverse objects
for(let i = 0 in obj){ console.log(i+':'+obj[i]); } // 数组元素:出现次数 // 1:3 // 2:3 // 3:1 // 4:1
The above is the detailed content of How to implement array deduplication and duplicate element statistics in ES6. For more information, please follow other related articles on the PHP Chinese website!