6

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
  • 1
    Have you tried some thing? You can get index using Array.indexOf('*') based on it create sub arrays Commented Sep 28, 2017 at 12:11
  • find the index of '*' then pass that index to Array.slice. Commented Sep 28, 2017 at 12:12
  • result = array.join("").split("*").map(function(d){return d.split("")}) Commented Sep 28, 2017 at 12:20

3 Answers 3

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));

Sign up to request clarification or add additional context in comments.

Comments

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'], '*')
)

Comments

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'], '*')
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.