1

I'm trying to keep a record array of a certain variable, but whenever I push that variable it doesn't push an instance of that variable, but the variable itself.

var array = [0,0,0];
var record = [];

record.push(array);
for(var i=0;i<array.length;i++) {
    array[i]++;
}
record.push(array);
console.log(record);
//I need record to be [[0,0,0],[1,1,1]], but it gives two copies of the latter
  • 1
    You need to copy the array into a new temporary one. – Dale K Oct 22 '18 at 01:28
  • It's not pushing the variable. It's pushing the array that the variable references. You only created two arrays in your code and one of them is `record`. If you want each row of record to be another array you need to create an array for every row. You could do that by copying `array` (with `array.slice(0)` for example), or by using another array literal in your loop and then filling it with the correct values. – Paul Oct 22 '18 at 01:32
  • Thanks, the slice function seems to be working. – jerbear doesnotcare Oct 22 '18 at 01:39

3 Answers3

1

You can use "slice" on the array (with optional "0" as first argument) to get a clone of it:

var array = [0,0,0];
var record = [];

record.push(array.slice(0));

for(var i=0;i<array.length;i++) {
    array[i]++;
}

record.push(array.slice(0));

console.log(record);
// record is: [[0, 0, 0], [1, 1, 1]]
Neii
  • 598
  • 2
  • 7
0

You can use a built-in function to do that:

var record = array.slice(0);

ref: https://davidwalsh.name/javascript-clone-array

Nikolay Vetrov
  • 624
  • 6
  • 17
0

Clone an Array

Array.slice is a more expensive operation (see this method comparison).
Instead, you can do something like so:

const array = [0,0,0];
const record = [Object.values(array)];

for(var i = 0; i < array.length; i++) {
    array[i]++;
}

record.push(array);

console.log(record);

UPDATE:
In order to make a copy of an array, there are many options that I can think of:

1) [...arr]
2) [].concat(arr);
3) arr.slice();
4) arr.map(i => i);
5) Array.of(...arr);
6) Object.values(arr);
7) Object.assign([], arr);
8) JSON.parse(JSON.stringify(arr));
etc...
Community
  • 1
  • 1
Lior Elrom
  • 19,660
  • 16
  • 80
  • 92