var arr = ['a', 'b', 'c', 'd', 'e', 'f']; var point = 'c';
How can I split the "arr" into two arrays based on the "point" variable, like:
['a', 'b']
and
['d', 'e', 'f']
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 1: Split Array Using slice() The for loop iterates through the elements of an array. During each iteration, the value of i is increased by chunk value (here 2). The slice() method extracts elements from an array where: The first argument specifies the starting index.
Splitting NumPy Arrays Splitting is reverse operation of Joining. Joining merges multiple arrays into one and Splitting breaks one array into multiple. We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.
var arr2 = ['a', 'b', 'c', 'd', 'e', 'f']; arr = arr2.splice(0, arr2.indexOf('c'));
To remove 'c' from arr2:
arr2.splice(0,1);
arr contains the first two elements and arr2 contains the last three.
This makes some assumptions (like arr2 will always contain the 'point' at first assignment), so add some correctness checking for border cases as necessary.
Sharing this convenience function that I ended up making after visiting this page.
function chunkArray(arr,n){ var chunkLength = Math.max(arr.length/n ,1); var chunks = []; for (var i = 0; i < n; i++) { if(chunkLength*(i+1)<=arr.length)chunks.push(arr.slice(chunkLength*i, chunkLength*(i+1))); } return chunks; }
Sample usage:
chunkArray([1,2,3,4,5,6],2); //returns [[1,2,3],[4,5,6]] chunkArray([1,2,3,4,5,6,7],2); //returns [[1,2,3],[4,5,6,7]] chunkArray([1,2,3,4,5,6],3); //returns [[1,2],[3,4],[5,6]] chunkArray([1,2,3,4,5,6,7,8],3); //returns [[1,2],[3,4,5],[6,7,8]] chunkArray([1,2,3,4,5,6,7,8],42);//over chunk //returns [[1],[2],[3],[4],[5],[6],[7],[8]]
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