Home > Web Front-end > JS Tutorial > How to implement array deduplication and duplicate element statistics in ES6

How to implement array deduplication and duplicate element statistics in ES6

不言
Release: 2018-09-27 16:14:24
Original
5593 people have browsed it

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));
Copy after login

2. Statistics

let count = 0;
let obj = {}; //最终返回的数据
dedupeArr.forEach(i=>{
    count = 0;
    arr1.forEach(j=>{
        if(i===j) count++;
    })
    obj[i] = count;//键名为i(数组元素),值为count(出现次数)
})
Copy after login

3. Traverse objects

for(let i = 0 in obj){
    console.log(i+':'+obj[i]);
}
// 数组元素:出现次数
// 1:3
// 2:3
// 3:1
// 4:1
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template