Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into two arrays

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'] 
like image 488
ellabeauty Avatar asked Mar 29 '12 21:03

ellabeauty


People also ask

How do I split an array into multiple arrays?

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.

How do you separate an array of arrays?

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.

How do you split an array into two arrays in Python?

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.


Video Answer


2 Answers

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.

like image 189
ramblinjan Avatar answered Oct 14 '22 17:10

ramblinjan


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]] 
like image 20
Julien Altieri Avatar answered Oct 14 '22 17:10

Julien Altieri