Many blocks by elements

How can I split an array into an element?

For example, lodash has this function, splitting arrays by length

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

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

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

which will give me

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

This is something like a split string for an array

+5
source share
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)); 
+4
source

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

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

Source: https://habr.com/ru/post/1272189/


All Articles