Skip to content Skip to sidebar Skip to footer

JavaScript Slice Method?

I want to slice elements of one array into a new left and right array. I am stuck on how to start this.

Solution 1:

You'll want to start with the "slice" method. Note that it returns a NEW array without changing the old array, so you'll want to go back and mutate the old array as well.

For instance:

var a = [1,2,3,4,5],
    b = a.slice(3);

a.length = 3;
// a is now [1,2,3]
// b is now [4,5]

Solution 2:

Given this array:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

If you want to split the array so that the first 4 items go to the left array and the rest to the right array, then do this:

var leftArr = arr.slice(0, 4);

and

var rightArr = arr.slice(4);

You can make a function that returns those two arrays based on the split-position:

function splitArr(arr, i) {
    return [ arr.slice(0, i), arr.slice(i) ];
}

Solution 3:

umm..... have you looked at .slice() ?

new_array = your_array.slice( start_index , end_index );

This creates a completely new array, not a reference.


Solution 4:

I'd use splice.

var a=[1,2,3,4,5,6];

var b=a.splice(3,a.length);


now a= [1,2,3]
and b=[4,5,6]

Solution 5:

From http://www.w3schools.com/jsref/jsref_slice_array.asp :

Syntax :

array.slice(start, end)

Example :

<script type="text/javascript">
  var fruits = ["Banana", "Orange", "Apple", "Mango"];
  document.write(fruits.slice(0,1) + "<br />");
  document.write(fruits.slice(1) + "<br />");
  document.write(fruits.slice(-2) + "<br />");
  document.write(fruits);
</script>

Output :

Banana
Orange,Apple,Mango
Apple,Mango
Banana,Orange,Apple,Mango

Post a Comment for "JavaScript Slice Method?"