5

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

Hayk Safaryan
  • 1,996
  • 3
  • 29
  • 51
  • 1
    Have you tried some thing? You can get index using `Array.indexOf('*')` based on it create sub arrays – Satpal Sep 28 '17 at 12:11
  • find the index of `'*'` then pass that index to [`Array.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). – Dan O Sep 28 '17 at 12:12
  • result = array.join("").split("*").map(function(d){return d.split("")}) – krishnar Sep 28 '17 at 12:20

3 Answers3

5

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));
Faly
  • 13,291
  • 2
  • 19
  • 37
1

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'], '*')
)
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

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'], '*')
)
Andrew Koval
  • 166
  • 1
  • 3