Chunking array not knowing the size of the subarray

Hello all,

I have an array where some values are repeated, but I don’t know, how many times. Each time it will be a different array.
I want to chunk it into subarrays, each one inlcuding only identical values.
I.e.

var array = [1,1,2,2,2,3,3,4];
var resultArr = [[1,1], [2,2,2], [3,3], [4]];

Could anyone help, please?

What approaches have you tried?

1 Like

Is array already sorted, so that all of the repeated numbers are grouped together alrready?

a suggested solution:

function chunkByValue(array) {
  // first gather information about the count of each element of the array
  const counts = array.reduce(
    // increment the number count in the countMap if already seen,
    //otherwise set its count to 1
    (countMap, n) => countMap.set(n, (countMap.get(n) || 0) + 1),
    // using an es6 Map because its keys can be anything including numbers.
    new Map()
  );
  return [...counts.entries()].reduce(
    // start from an empty array and add subarrays of each number
    // with a length corresponding to its count in the original array
    (result, [n, count]) => [...result, Array(count).fill(n)],
    []
  );
}

console.log(chunkByValue([1, 1, 2, 2, 2, 3, 3, 4]));
// -> [ [ 1, 1 ], [ 2, 2, 2 ], [ 3, 3 ], [ 4 ] ]
const array = [1,1,2,2,2,3,3,4];

let previous = {};
let resultArr = [];

array.forEach(function(num){

  if (previous[num]){

      previous[num].push(num);

  }

  if (!previous[num]){

      previous[num] = [num];

  }

});

for (val in previous){

  resultArr.push(previous[val]);

}

console.log(resultArr);

Works regardless of order. Time complexity O(n).

Thank you very much, everyone.

I haven’t thought about creating an object, i.e. ‘previous’, but that’s a very smart approach.