Chunk array by element

Viewed 191

How can I chunk array by element?

For example lodash has this function chunking arrays by lengths

_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]

_.chunk(['a', 'b', 'c', 'd'], 3);
// => [['a', 'b', 'c'], ['d']]

So I have an array like this ['a', 'b', '*', 'c'] can I do something like

chunk(['a', 'b', '*', 'c'], '*')

which will give me

[['a', 'b'], ['c']]

It is something like string split for array

3 Answers

You can use array.Reduce:

var arr = ['a', 'b', '*', 'c'];
var c = '*';
function chunk(arr, c) {
    return arr.reduce((m, o) => {
        if (o === c) {
            m.push([]);
        } else {
            m[m.length - 1].push(o);
        }
        return m;
    }, [[]]);
}
console.log(chunk(arr, c));

Using traditional for loops:

function chunk(inputArray, el){   

   let result = [];
   let intermediateArr = [];

   for(let i=0; i<inputArray.length; i++){

      if(inputArray[i] == el)
      {
         result.push(intermediateArr);
         intermediateArr=[];
   
      }else {
         intermediateArr.push(inputArray[i]);
      }
    
   }

   if(intermediateArr.length>0) {
      result.push(intermediateArr);
   }

   return result;
       
}

console.log(
  chunk(['a', 'b', '*', 'c', 'd', 'e', '*', 'f'], '*')
)

A little recursion.

function chunk (arr, el) {
  const index = arr.indexOf(el);
  var firstPart;
  var secondPart;
  if(index > -1) {
    firstPart = arr.slice(0, index);
      secondPart = arr.slice(index + 1);
  }
  if(secondPart.indexOf(el) > -1) {
   return [firstPart].concat(chunk(secondPart, el));
  }
  return [firstPart, secondPart];
}

console.log(
  chunk(['a', 'b', '*', 'c', 'd', 'e', '*', 'f'], '*')
)

Related