Skip to content

JavaScript split array | into a chunk, two based on condition

  • by

JavaScript split array can be done by using a slice() method. The slice() method returns a shallow copy of a portion of an array into a new array object.

In the slice method, you have to pass the start and end of the argument. It returns the value of indexed at the given start argument and ends at, but excluding the given end argument.

Syntax: array.slice(start, end)

Note: split() is a method of the String object, not of the Array object. So you can’t s split array by using the split method.

Examples of JavaScript split array

The array’s first element is at index 0. Let’s examples of how to JS split array into chunks.

Array into many smaller Arrays

The array.slice method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.

See below example of Split array into chunks in JS.

<!DOCTYPE html>
<html>
  <head>
    <script>
    	array = ["A 1","B 2","C 3"];

        var i,j,temparray,chunk = 10;

		for (i=0,j=array.length; i<j; i+=chunk) {
    	temparray = array.slice(i,i+chunk);

    	console.log(temparray)
		}
    </script>
  </head>   

</html>
JavaScript split array into multiple array

How to javascript split array into two-part

Use the slice() method to get the one by one portion of an array into a new array object.

<!DOCTYPE html>
<html>
  <head>
    <script>
    	var plans=['a', 'b', 'c', 'd' ];

        var monthly_plans = plans.slice(0, 2);
		var yearly_plans = plans.slice(2);

    	console.log(monthly_plans)
		console.log(yearly_plans)

    </script>
  </head>   

</html>

Output:

split an array into two arrays in javascript

Q: How to javascript split array into two based on a condition?

Answer: Here is a code of split an array into two arrays based on odd/even position.

var Arr1 = [1,1,2,2,3,8,4,6],
    Arr2 = [],
    Arr3 = [];

for (var i=0;i<Arr1.length;i++){
    if ((i+2)%2==0) {
        Arr3.push(Arr1[i]);
    }
    else {
        Arr2.push(Arr1[i]);
    }
}

console.log(Arr2);

Output: [1, 2, 8, 6]

Do comment if you have any questions and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading