user689290
user689290

Reputation: 93

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.

Upvotes: 5

Views: 8263

Answers (6)

Šime Vidas
Šime Vidas

Reputation: 186103

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) ];
}

Upvotes: 2

kennebec
kennebec

Reputation: 104850

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]

Upvotes: 1

Chris Nielsen
Chris Nielsen

Reputation: 14758

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]

Upvotes: 4

invalidsyntax
invalidsyntax

Reputation: 650

<html>
<body>

<script type="text/javascript">

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

</script>

</body>
</html>

(Reference from w3schools): http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_slice_array

Upvotes: 0

Sandro Munda
Sandro Munda

Reputation: 41078

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

Upvotes: 0

jondavidjohn
jondavidjohn

Reputation: 62412

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

new_array = your_array.slice( start_index , end_index );

This creates a completely new array, not a reference.

Upvotes: 2

Related Questions