Home >Web Front-end >JS Tutorial >Count the number of occurrences of repeated elements in JavaScript
The editor below will share with you an example of deduplicating a JavaScript array and counting the number of occurrences of repeated elements. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look.
1. Method one
var arr = [1, 2, 3, 1, 2, 4]; function arrayCnt(arr) { var newArr = []; for(var i = 0; i < arr.length; i++) { if(newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]) } } var newarr2 = new Array(newArr.length); for(var t = 0; t < newarr2.length; t++) { newarr2[t] = 0; } for(var p = 0; p < newArr.length; p++) { for(var j = 0; j < arr.length; j++) { if(newArr[p] == arr[j]) { newarr2[p]++; } } } for(var m = 0; m < newArr.length; m++) { console.log(newArr[m] + "重复的次数为:" + newarr2[m]); } } arrayCnt(arr);
2. Method two (set method Remove duplicates)
var arr = [1, 2, 3, 1, 2, 4]; function arrayCnt(arr) { var newArr = []; //使用set进行数组去重 newArr = [...new Set(arr)]; var newarr2 = new Array(newArr.length); for(var t = 0; t < newarr2.length; t++) { newarr2[t] = 0; } for(var p = 0; p < newArr.length; p++) { for(var j = 0; j < arr.length; j++) { if(newArr[p] == arr[j]) { newarr2[p]++; } } } for(var m = 0; m < newArr.length; m++) { console.log(newArr[m] + "重复的次数为:" + newarr2[m]); } } arrayCnt(arr);
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to jump to the previous page in vue
How to implement dynamic loading using treeview in the Bootstrap framework Data
About website generation chapter directory code example
Detailed introduction to Vue data binding
Regarding the use of Vue high-order components
Is using JavaScript a better solution than asynchronous implementation?
Using Koa to build projects through Node.js
Detailed interpretation of React Native Flexbox layout
The above is the detailed content of Count the number of occurrences of repeated elements in JavaScript. For more information, please follow other related articles on the PHP Chinese website!