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
Splitting the Array Into Even Chunks Using slice() Method The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.
Example 2: Split Array Using splice() In the above program, the while loop is used with the splice() method to split an array into smaller chunks of an array. In the splice() method, The first argument specifies the index where you want to split an item.
To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.
The array_chunk() function is an inbuilt function in PHP which is used to split an array into parts or chunks of given size depending upon the parameters passed to the function. The last chunk may contain fewer elements than the desired size of the chunk.
Here is my solution: function chunk (arr, len) { var chunks = [], i = 0, n = arr.length; while (i < n) { chunks.push (arr.slice (i, i += len)); } return chunks; } // Optionally, you can do the following to avoid cluttering the global namespace: Array.chunk = chunk;
array_chunk(array$array, int$length, bool$preserve_keys= false): array Chunks an array into arrays with lengthelements.
The last chunk may be smaller than chunkSize. For example when given an array of 12 elements the first chunk will have 10 elements, the second chunk only has 2. Note that a chunkSize of 0 will cause an infinite loop. Nope, the last chunk should just be smaller than the others. @Blazemonger, indeed!
Here is an example where I split an array into chunks of 2 elements, simply by splicing chunks out of the array until the original array is empty.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With