0

I am looking to remove the first two elements of an array and use both the new array and the model later in my code. My issue is that splice() is even altering my arrayModel in my code.

Here is my code

var arrayModel = ['a','b','c','d']

function dontAlterMyModel (arrayModel) {
  arrayTemp = arrayModel
  arrayTemp.splice(0, 2)
  console.log("arrayModel", arrayModel)
  console.log("arrayTemp", arrayTemp)
  return
}

dontAlterMyModel(arrayModel)

Here is the result:

arrayModel [ 'c', 'd' ]
arrayTemp [ 'c', 'd' ]

Whereas I'd like to have:

arrayModel [ 'a', 'b', 'c', 'd' ]
arrayTemp [ 'c', 'd' ]

I tried to used other methods.

Using shift() twice was also altering the model

arrayTemp = array.slice(2) was giving me back the opposite of what I wanted: [ 'a', 'b']

How should I proceed? Thanks for your help!

Quentin Del
  • 1,485
  • 2
  • 18
  • 32
  • 3
    [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Andreas Apr 11 '17 at 16:37
  • I think you are correct @Andreas. The problem isn't that this lacks a solution but rather the person doesn't understand why this is happening. – misha130 Apr 11 '17 at 16:43

3 Answers3

1

Array#splice mutates the original array. I would suggest you to use Array#slice and store the new array inside new variable.

var arrayModel = ['a','b','c','d']

function dontAlterMyModel (arrayModel) {
  arrayTemp = arrayModel;
  var newArr = arrayTemp.slice(-2);
  console.log("arrayModel", arrayModel);
  console.log("arrayTemp", newArr);
}

dontAlterMyModel(arrayModel)
kind user
  • 40,029
  • 7
  • 67
  • 77
0

Copy original array by using object assign

  arrayTemp = Object.assign([], arrayModel).splice(0,2)
misha130
  • 5,457
  • 2
  • 29
  • 51
0

you can use minus numbers in slice

var a = ['a', 'b', 'c', 'd'];
var b = a.slice(-2);

console.log(a, b);
Nima Hakimi
  • 1,382
  • 1
  • 8
  • 23