如何使用ECMAScript2015选项。
const a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
const aCount = new Map([...new Set(a)].map(
x => [x, a.filter(y => y === x).length]
));
aCount.get(5)
aCount.get(2)
aCount.get(9)
aCount.get(4)
这个例子将输入数组传递给
Set
构造函数,创建一个包含
唯一值的集合。然后
展开语法将这些值扩展到一个新数组中,以便我们可以调用
map
并将其转换为一个二维数组
[value, count]
对,即以下结构:
Array [
[5, 3],
[2, 5],
[9, 1],
[4, 1]
]
新数组随后传递给
Map
构造函数,从而产生一个
可迭代对象:
Map {
5 => 3,
2 => 5,
9 => 1,
4 => 1
}
Map
对象的优点是它保留数据类型 - 也就是说,aCount.get(5)
将返回3
,但aCount.get("5")
将返回undefined
。 它还允许任何值/类型作为键,这意味着该解决方案也适用于对象数组。
function frequencies( a){
return new Map([...new Set(a)].map(
x => [x, a.filter(y => y === x).length]
));
}
let foo = { value: 'foo' },
bar = { value: 'bar' },
baz = { value: 'baz' };
let aNumbers = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4],
aObjects = [foo, bar, foo, foo, baz, bar];
frequencies(aNumbers).forEach((val, key) => console.log(key + ': ' + val));
frequencies(aObjects).forEach((val, key) => console.log(key.value + ': ' + val));
if (arr.indexOf(value) == arr.lastIndexOf(value))
。 - Rodrigoramda.js
来轻松实现这一点。R.countBy(r=> r)(ary)```
- Eshwar Prasad Yaddanapudiarr.filter(x => x===5).length
会返回3
,表示数组中有 '3' 个数字 '5'。 - noobninja