1

I've got an Array:

var Arr = [1, 4, 8, 9];

At some point later in the code this happens:

Arr.push(someVar);

Here instead of pushing a new value, I want to replace the entire contents of Arr with someVar. (i.e. remove all previous contents so that if I console.logged() it I'd see that Arr = [someVar]

How could this be achieved??

Allen S
  • 3,471
  • 4
  • 34
  • 46

5 Answers5

2

Try:

Arr.length = 0;
Arr.push(someVar);

Read more: Difference between Array.length = 0 and Array =[]?

Community
  • 1
  • 1
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
1

Try this:

Arr = [somevar];

Demo: http://jsfiddle.net/UbWTR/

Josh
  • 2,835
  • 1
  • 21
  • 33
0

you can assign the value just like this

var Arr = [1, 4, 8, 9]; //first assignment

Arr = [other value here]

It will replace array contents.

I hope it will help

Sonu Sindhu
  • 1,752
  • 15
  • 25
  • This replaces the array with a value, not with a new array containing the value. (note - comment based on version without square brackets) – Adrian Wragg Jul 30 '13 at 11:17
0

you want splice to keep the same instance: arr.splice(0, arr.length, someVar)

kares
  • 7,076
  • 1
  • 28
  • 38
0

You can do like this

var Arr = [1, 4, 8, 9];  // initial array


Arr  = [] // will remove all the elements from array

Arr.push(someVar);  // Array with your new value
defau1t
  • 10,593
  • 2
  • 35
  • 47