Counting the occurrences / frequency of array elements

前端 未结 30 2106
甜味超标
甜味超标 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:33

    Using MAP you can have 2 arrays in the output: One containing the occurrences & the other one is containing the number of occurrences.

    const dataset = [2,2,4,2,6,4,7,8,5,6,7,10,10,10,15];
    let values = [];
    let keys = [];
    
    var mapWithOccurences = dataset.reduce((a,c) => {
      if(a.has(c)) a.set(c,a.get(c)+1);
      else a.set(c,1);
      return a;
    }, new Map())
    .forEach((value, key, map) => {
      keys.push(key);
      values.push(value);
    });
    
    
    console.log(keys)
    console.log(values)

提交回复
热议问题