在Javascript中,我试图采取数字值的初始数组,并计算其中的元素。理想情况下,结果将是两个新数组,第一个数组指定每个唯一元素,第二个数组包含每个元素出现的次数。但是,我愿意听取关于输出格式的建议。
例如,如果初始数组是:
5, 5, 5, 2, 2, 2, 2, 2, 9, 4
然后将创建两个新数组。第一个将包含每个唯一元素的名称:
5, 2, 9, 4
第二个将包含该元素在初始数组中出现的次数:
3, 5, 1, 1
因为数字5在初始数组中出现了三次,数字2出现了五次,9和4都出现了一次。
我一直在寻找解决方案,但似乎没有一个可行,而且我自己尝试过的每件事最后都出奇地复杂。任何帮助都将不胜感激!
谢谢:)
使用MAP,您可以在输出中有两个数组:一个包含出现次数,另一个包含出现次数。
常量数据集=(2、2、4、2、6、4、7、8、5、6、7、10、10、10、15);
Let values = [];
Let keys = [];
var mapwithoccurs = dataset.reduce((a,c) => {
如果(a.has (c)) a.set (c, a.get (c) + 1);
其他a.set (c, 1);
返回一个;
}, new Map())
.forEach((value, key, map) => {
keys.push(关键);
values.push(价值);
});
console.log(键)
console.log(值)
你可以使用一个对象来保存结果:
Const arr = [5,5,5,2,2,2,2,2,2,2,2,9,4];
Const counts = {};
(const num of arr) {
Counts [num] = Counts [num] ?计数[num] + 1: 1;
}
console.log(重要);
Console.log(计数[5],计数[2],计数[9],计数[4]);
所以,现在你的counts对象可以告诉你一个特定数字的计数是多少:
console.log(counts[5]); // logs '3'
如果您想获取成员数组,只需使用keys()函数即可
keys(counts); // returns ["5", "2", "9", "4"]
不要使用两个数组的结果,使用一个对象:
a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
result = { };
for(var i = 0; i < a.length; ++i) {
if(!result[a[i]])
result[a[i]] = 0;
++result[a[i]];
}
然后结果将看起来像:
{
2: 5,
4: 1,
5: 3,
9: 1
}
使用ramda.js有一个更好更简单的方法可以做到这一点。
代码示例
Const ary = [5,5,5,2,2,2,2,2,2,2,2,2,9,4];
R.countBy (r = > r)(必要)
countBy documentation是at documentation
一行ES6解决方案。这么多的答案使用对象作为地图,但我看不到任何人使用实际的地图
const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
使用map.keys()获取唯一元素
使用map.values()来获取事件
使用map.entries()获取对[元素,频率]
Var arr = [5,5,5,2,2,2,2,2,2,2,9,4]
Const map = arr。Reduce ((acc, e) => acc。set(e, (acc.get(e) || 0) + 1), new Map());
console.info([…map.keys ()))
console.info([…map.values ()))
console.info([…]. entry ()))
我知道这个问题是旧的,但我意识到有太少的解决方案,你得到的计数数组要求用最小的代码,所以这是我的
// The initial array we want to count occurences
var initial = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
// The count array asked for
var count = Array.from(new Set(initial)).map(val => initial.filter(v => v === val).length);
// Outputs [ 3, 5, 1, 1 ]
你可以从初始数组中得到集合
var set = Array.from(new Set(initial));
//set = [5, 2, 9, 4]