Counting the occurrences / frequency of array elements

前端 未结 30 2583
甜味超标
甜味超标 2020-11-21 06:47

In Javascript, I\'m trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each

30条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:35

    var array = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
    
    function countDuplicates(obj, num){
      obj[num] = (++obj[num] || 1);
      return obj;
    }
    
    var answer = array.reduce(countDuplicates, {});
    // answer => {2:5, 4:1, 5:3, 9:1};
    

    If you still want two arrays, then you could use answer like this...

    var uniqueNums = Object.keys(answer);
    // uniqueNums => ["2", "4", "5", "9"];
    
    var countOfNums = Object.keys(answer).map(key => answer[key]);
    // countOfNums => [5, 1, 3, 1];
    

    Or if you want uniqueNums to be numbers

    var uniqueNums = Object.keys(answer).map(key => +key);
    // uniqueNums => [2, 4, 5, 9];
    

提交回复
热议问题