在Javascript中,我试图采取数字值的初始数组,并计算其中的元素。理想情况下,结果将是两个新数组,第一个数组指定每个唯一元素,第二个数组包含每个元素出现的次数。但是,我愿意听取关于输出格式的建议。

例如,如果初始数组是:

5, 5, 5, 2, 2, 2, 2, 2, 9, 4

然后将创建两个新数组。第一个将包含每个唯一元素的名称:

5, 2, 9, 4

第二个将包含该元素在初始数组中出现的次数:

3, 5, 1, 1

因为数字5在初始数组中出现了三次,数字2出现了五次,9和4都出现了一次。

我一直在寻找解决方案,但似乎没有一个可行,而且我自己尝试过的每件事最后都出奇地复杂。任何帮助都将不胜感激!

谢谢:)


当前回答

你可以使用一个对象来保存结果:

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"]

其他回答

这是一个经典的计算数组的方法。

var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
var counted = [], count = [];
var i = 0, j = 0, k = 0;
while (k < arr.length) {
    if (counted.indexOf(arr[k]) < 0) {
        counted[i] = arr[k];
        count[i] = 0;
        for (j = 0; j < arr.length; j++) {
            if (counted[i] == arr[j]) {
                count[i]++;
            }
        }
        i++;
    } else {
        k++;
    }
}

如果您希望得到字母顺序的结果,可以先对其排序,但如果您希望保留输入数据的顺序,则可以尝试这种方法。嵌套循环可能比本页上的其他一些方法要慢一些。

var aa = [1,3,5,7,3,2,4,6,8,1,3,5,5,2,0,6,5,9,6,3,5,2,5,6,8];
var newArray = {};
for(var element of aa){
  if(typeof newArray[element] === 'undefined' || newArray[element] === null){
    newArray[element] = 1;
  }else{
    newArray[element] +=1;
  }
}

for ( var element in newArray){
  console.log( element +" -> "+ newArray[element]);
}

一行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 ()))

返回一个可排序的数组:

let array = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4] let reducedArray = array.reduce( (acc, curr, _, arr) => { if (acc.length == 0) acc.push({item: curr, count: 1}) else if (acc.findIndex(f => f.item === curr ) === -1) acc.push({item: curr, count: 1}) else ++acc[acc.findIndex(f => f.item === curr)].count return acc }, []); console.log(reducedArray.sort((a,b) => b.count - a.count )) /* Output: [ { "item": 2, "count": 5 }, { "item": 5, "count": 3 }, { "item": 9, "count": 1 }, { "item": 4, "count": 1 } ] */

根据@adamse和@pmandell的回答(我支持),在ES6中,你可以在一行中完成:

2017年编辑:我使用||来减少代码大小,使其更具可读性。

var =[7, 1、7、2、2、7、3、3、3、7、7、7、7]; 警报(JSON.stringify ( a.reduce ((r, k) = > {[k] = 1 + r [k] | | 1;返回r}, {}) ));


它可以用来计数字符:

var s =“唵嘛呢叭咪吽”; 警报(JSON.stringify ( s.split(”)。Reduce ((a, c)=>{a[c]++?0:a[c]=1;返回a},{}) ));