目前,我有一个数组如下:
var uniqueCount = Array();
几步之后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
我该如何计算数组中有多少个a、b、c?我希望得到这样的结果:a = 3
b = 1
c = 2
d = 2
目前,我有一个数组如下:
var uniqueCount = Array();
几步之后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
我该如何计算数组中有多少个a、b、c?我希望得到这样的结果:a = 3
b = 1
c = 2
d = 2
const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)
(counts[x] || 0) + 1
是如何计数的呢? - jsduniyacounts[x] || 0
如果 counts[x]
已经被设置,则返回它的值;否则返回 0
。通过加1并将其重新设置到对象中,计数就完成了。 - Constantiniusreduce
方法:var counts = your_array.reduce((map, val) => {map[val] = (map[val] || 0)+1; return map}, {} );
- Alberto89类似这样:
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);
如果您不希望在旧的浏览器中发生错误,请使用简单的for循环代替forEach。
uniqueCount.forEach(function(value, index) { count[value] = (count[value] || 0) + 1; });
- Pedro Ferreiravar 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:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
编辑:
使用箭头函数中的逗号操作符,我们可以将其写成一行代码:
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce((cnt, cur) => (cnt[cur] = cnt[cur] + 1 || 1, cnt), {});
// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
prev[cur] = (prev[cur] || 0) + 1;
- keyboard-warrior0
开始递增prev[cur]
。(如果prev[0]
未定义,则使用值0
代替)。你也可以使用表达式(prev[cur] + 1) || 1
,但这并没有太大区别。 - isnot2badfunction 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();
你也可以使用高阶函数来执行操作。 查看这个答案
for (var i = 0; i <= array_elements.length; i++) {
或者<=
而不是<
即可。 - heckascript简单就是美,一个变量,一个函数 :)
const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {});
console.log(counts);
arr.sort().reduce((
,你就得到了完美的解决方案!(但我还是给你点赞了) - undefined
// 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]);
使用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));
Map()
,而我通常会与Array.prototype.reduce()
结合使用:
const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());
console.log(...result);
注意,如果想在较旧的浏览器中使用它,您将需要使用polyfill库中的Map()
。
get
和set
函数来自于Map
对象。但是初始累加器不是Map
对象,那么为什么归约器的缩减版本需要一个呢? - Antoine NedelecMap
对象;请参见 reduce 的第二个参数。Map.prototype.set
返回 map 对象,而 Map.prototype.get
返回 undefined
或提供给它的任何键的值。这使我们可以获取每个字母的当前计数(如果未定义,则为 0
),然后将其增加一,然后将该字母的计数设置为新计数,这将返回 map 并成为新的累加器值。 - aendra我认为这是在数组中计算相同值出现次数的最简单方法。
var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
const arr = ['a','d','r','a','a','f','d'];
const result = arr.reduce((json,val)=>({...json, [val]:(json[val] | 0) + 1}),{});
console.log(result)
//{ a:3,d:2,r:1,f:1 }
{}
这种类型的map,而不是函数式编程中的map
。 - Matt Ball