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,351
  • 4
  • 31
  • 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
  • 40,230
  • 12
  • 130
  • 145
1

Try this:

Arr = [somevar];

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

Flame Trap
  • 2,745
  • 1
  • 20
  • 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,535
  • 14
  • 22
  • 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
  • 6,896
  • 1
  • 26
  • 37
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,457
  • 2
  • 33
  • 46