2

I have this (sub)object called products.original.

which I then extract to a new object called productArray:

var productArray = [];

productArray = products.original;

/*some calculations here*/

//sort the object by lowest score
productArray.sort(function(a, b) {return a.score - b.score;});

Finally, I extract the first three cells in productArray to a third object called resultArray:

var resultArray= [];        
resultArray = productArray.splice(0,3);

To my surprise, this reduces the length of products.original by 3 (the splice). Why? And what do I do to hinder this? Thanks in advance.

jenswirf
  • 7,087
  • 11
  • 45
  • 65
  • 2
    You should get rid of the `= []`. there is no point in creating an array and assigning it to a variable if you are going to assign a different array to that variable on the next line. – Quentin Feb 24 '12 at 10:25
  • Does this answer your question? [Copy array by value](https://stackoverflow.com/questions/7486085/copy-array-by-value) – Ivar Mar 31 '22 at 11:57

5 Answers5

2

You did not copy the array, but just the reference to it. So all your operations are still performed on the original object. For real cloning use slice.

 productArray = products.original.slice(0);
georg
  • 211,518
  • 52
  • 313
  • 390
Sirko
  • 72,589
  • 19
  • 149
  • 183
2

Try this way:

productArray = products.original.slice();

In javascript object are passed by reference.

dfsq
  • 191,768
  • 25
  • 236
  • 258
2

splice:

Changes the content of an array, adding new elements while removing old elements.

You want slice:

Returns a one-level deep copy of a portion of an array.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

This is expected in JavaScript. This post will help you for your issue.

Community
  • 1
  • 1
Ved
  • 8,577
  • 7
  • 36
  • 69
0

the line

productArray = products.original;

doesnt actually copy products.original into productArray. Instead it copies a reference. This means each time you are changing productArray, you are also changing the original object. In order to (deep) copy a nested object you either have to do something complicated like iterating over the members of the object, check if they are arrays or objects (which will be copied by reference), iterate over those and copy the simple data types. The alternative is using underscore or jquery which provide copy functionality. Judging from your sorting function it appears that your array only contains numbers. In this case slice will do the trick.

See here for the jquery example (Deep) copying an array using jQuery

Community
  • 1
  • 1
joidegn
  • 1,078
  • 9
  • 19