Paran0a
Paran0a

Reputation: 3447

Splice also affecting initial array

I want to split my array in half and save the results of that in another array, But without affecting the original.

So if I had [1,3,9,5] I would want to save it in a variable. Then I would create new array and copy the initial one in it. Then I would split that new array in half.

Meaning in the end I would have 2 array like this

initial [1,3,9,5]
halved [1,3]

The problem is that initial one is also splitted and I get 2 array with each one holding half the values.

var initial = [1,3,9,5];

var half = initial;

half = half.splice(0, Math.floor(half.length / 2));

console.log(initial);
console.log(half);

Upvotes: 2

Views: 86

Answers (5)

Sebastien Daniel
Sebastien Daniel

Reputation: 4778

When splitting an array there are two prototype methods:

  • splice: a destructive version which affects the original array.
  • slice: a pure version, which returns a new array without affecting the array on which it operates.

var half = initial.slice(0,Math.floor(half.length / 2));

Just replace your use of splice with slice and you're good to go.

For more information, I invite you to consult the excellent MDN document for Array.splice and MDN document for Array.slice

Upvotes: 1

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19070

Check the following:

Option 1 Creating a copy of the initial array

var initial = [1,3,9,5];

var half = [].concat(initial);

half = half.splice(0, Math.floor(half.length / 2));

console.log(initial);
console.log(half);

The [].concat(initial) allows to create a copy of the initial array.

Option 2 Do not modify the initial array, but use slice method

var initial = [1,3,9,5];

var half = initial.slice(0, Math.floor(half.length / 2));

console.log(initial);
console.log(half);

Upvotes: 1

The Process
The Process

Reputation: 5953

You can do it like this

var initial = [1,3,9,5];

var half = initial.slice(0, Math.floor(initial.length / 2));

console.log(initial); 
console.log(half);  

Upvotes: 1

Sebastian Simon
Sebastian Simon

Reputation: 19475

var half = initial;

copies the reference of initial to half. They’re the same array.

Either copy the values of the array with var half = initial.slice(); or get the half right away with

var initial = [1, 3, 9, 5];
var half = initial.slice(0, Math.floor(initial.length / 2));

Upvotes: 1

jdabrowski
jdabrowski

Reputation: 1965

When you do var half = initial; you only pass a reference, not copy an array. You need to use other method to copy an array, for example:

var half = initial.slice();

Upvotes: 0

Related Questions