Split an array in JavaScript
This post will discuss how to split an array into two subarrays of a fixed size, or based on a given condition in JavaScript.
There are several ways to split an array into two subarrays in JavaScript, depending on the size and criteria of the subarrays. Here are some examples of how to split an array into two subarrays in JavaScript given different scenarios:
1. Using slice() function
If we want to split an array into two subarrays of a fixed size, we can use the slice() function to create shallow copies of the original array from a given start and end index. For example, if we have an array and we want to split it into two subarrays of size 3, we can do:
|
1 2 3 4 5 6 7 8 |
var arr = [1, 2, 3, 4, 5, 6]; var half = (arr.length + 1) / 2; var subarr1 = arr.slice(0, half); var subarr2 = arr.slice(half); console.log(subarr1); // [1, 2, 3] console.log(subarr2); // [4, 5, 6] |
2. Using a condition
If we want to split an array into two subarrays based on a given condition or function that returns true or false for each element, we can use the filter() function to create new arrays that contain only the elements that satisfy or do not satisfy the condition. For example, if we have an array and we want to split it into two subarrays based on whether the elements are even or odd, we can do:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var arr = [1, 2, 3, 4, 5, 6]; var isEven = function(num) { return num % 2 === 0; }; var subarr1 = arr.filter(isEven); var subarr2 = arr.filter(function(num) { return !isEven(num); }); console.log(subarr1); // [2, 4, 6] console.log(subarr2); // [1, 3, 5] |
3. Using a separator
If we want to split an array into two subarrays based on a given separator value or values, we can use a loop to iterate over the array and push the elements into different subarrays depending on whether they match the separator or not. For example, if we have an array var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and we want to split it into two subarrays based on the separators 3, 6, and 9, we can do:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var subarr1 = []; var subarr2 = []; var separators = [3, 6, 9]; for (var i = 0; i < arr.length; i++) { var item = arr[i]; if (separators.indexOf(item) > -1) { // if the item is a separator, switch to the other subarray var temp = subarr1; subarr1 = subarr2; subarr2 = temp; } else { // otherwise, push the item to the current subarray subarr1.push(item); } } console.log(subarr1); // [4, 5, 10] console.log(subarr2); // [1, 2, 7, 8] |
Output:
subarr1 = [5, ‘whazzup?’, {}], subarr2 = [34.6]
That’s all about splitting arrays into two subarrays in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)