javascript 如何在javascript中计算数组中的重复值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19395257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count duplicate value in an array in javascript
提问by detno29
Currently, I got an array like that:
目前,我得到了一个这样的数组:
var uniqueCount = Array();
After a few steps, my array looks like that:
几步后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
How can I count how many a,b,c are there in the array? I want to have a result like:
如何计算数组中有多少 a、b、c?我想要这样的结果:
a = 3
b = 1
c = 2
d = 2
etc.
等等。
采纳答案by Vinay Pratap Singh
function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
count();
You can use higher-order functions too to do the operation.See this answer
您也可以使用高阶函数来进行运算。看到这个答案
回答by SheetJS
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
回答by loxxy
Something like this:
像这样的东西:
uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
Use a simple for loop instead of forEach if you don't want this to break in older browsers.
如果您不想在旧浏览器中中断,请使用简单的 for 循环而不是 forEach。
回答by isnot2bad
I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):
我偶然发现了这个(非常古老的)问题。有趣的是,最明显和优雅的解决方案(恕我直言)不见了:Array.prototype.reduce(...)。自大约 2011 年(IE)或更早(所有其他浏览器)以来,所有主要浏览器都支持此功能:
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
// map is an associative array mapping the elements to their frequency:
document.write(JSON.stringify(map));
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
回答by dinigo
Single line based on reduce array function
基于reduce数组函数的单行
const uniqueCount = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] | 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));
回答by Shannon Hochkins
Simple is better, one variable, one function :)
简单更好,一个变量,一个函数:)
const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {});
回答by Dmytro Kozlovskyi
I think this is the simplest way how to count occurrences with same value in array.
我认为这是如何计算数组中具有相同值的出现次数的最简单方法。
var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
回答by Erik Martín Jordán
// Initial array
let array = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
// Unique array without duplicates ['a', 'b', ... , 'h']
let unique = [...new Set(array)];
// This array counts duplicates [['a', 3], ['b', 2], ... , ['h', 3]]
let duplicates = unique.map(value => [value, array.filter(str => str === value).length]);
回答by Ryan Luu
// new example.
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];
function findOdd(para) {
var count = {};
para.forEach(function(para) {
count[para] = (count[para] || 0) + 1;
});
return count;
}
console.log(findOdd(str));
回答by Pablo Souza
You can solve it without using any for/while loops ou forEach.
您可以在不使用任何 for/while 循环或 forEach 的情况下解决它。
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
希望对你有帮助!