-3

I want to count the number of occurrences of numbers from an array and put it into an array on its index, for example:

[1,2,0,0,0,1,5,4,2,6,1]

would give:

[3,3,2,0,1,1,1]

I tried to do it with map and push but the solution sound really archaic.

Dale K
  • 25,246
  • 15
  • 42
  • 71
heisenberg7584
  • 563
  • 2
  • 10
  • 30
  • 2
    you may post what you had tried already as well – Mechanic May 01 '20 at 18:05
  • Does this answer your question? [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) – ASDFGerte May 01 '20 at 18:09

3 Answers3

0

actually it is really easy using reduce with an object and the user values to get the values of the object.

const numbers = [1, 2, 0, 0, 0, 1, 5, 4, 2, 6, 1];

const reducer = (accum, current) => {
  if (accum[current]) {
    // if the value already has a count, we add one.
    accum[current] += 1;
  } else {
    // if we haven't counted that number, we create the entry and init with 1.
    accum[current] = 1;
  }
  return accum;
}

const resultObj = numbers.reduce(reducer, {})
// we get an object that has the form of
// { number: counts}

const result = Object.values(resultObj);

console.log(resultObj);
console.log(result);
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
  • I like this approach the most. It is much more readable compare to other suggestions –  May 02 '20 at 10:32
0

You could reduce the array and fill unknown indices with zeroes. Then increment the value at index.

var data = [1, 2, 0, 0, 0, 1, 5, 4, 2, 6, 1],
    result = data.reduce((r, i) => {
        while (r.length <= i) r[r.length] = 0;
        ++r[i];
        return r;
    }, [])

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can find the max element in the array, use Array#reduce with the accumulator as Array of size max + 1, for each element in the loop +1 the index value

let arr = [1, 2, 0, 0, 0, 1, 5, 4, 2, 6, 1];
let max = Math.max(...arr);
let out = arr.reduce((acc, i) => (acc[i]++, acc), Array(max + 1).fill(0));
console.log(out)
AZ_
  • 3,094
  • 1
  • 9
  • 19