0

I have been having some problems with this JS code.

The code is supposed to generate an array of random voltages (in the volts array), and then create a new array (the sortedVolts array) where the volts are sorted by lowest to highest.

The problem is that my code is sorting not only the sortedVolts array, but also the volts array, which is supposed to remain unsorted. Why is this happening?

var volts = [];
var sortedVolts;

for (var count = 0; count < 3; count++) {
    volts.push(Math.floor(Math.random() * 100));
}
sortedVolts = volts;
sortedVolts.sort();
console.log('UNSORTED', volts);
console.log('SORTED', sortedVolts);
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
Oreo
  • 103
  • 3
  • 1
    `sortedVolts = volts.slice() // creates a new array, or the two array would be same object.` – Sheepy Mar 22 '18 at 04:05

3 Answers3

1

You are assigning volts to the sortedVolts variable. You should copy the array instead using slice(). Answered in this question.

1

sortedVolts = volts does not create a copy of the array, it creates another variable which references the same array.

To make it work, you need to make atleast a shallow copy of volts, which can be done my sortedVolts = [ ...volts ]

var volts = [];
var sortedVolts;

for (var count = 0; count < 3; count++) {
    volts.push(Math.floor(Math.random() * 100));
}
sortedVolts = [...volts]; //CHANGE THIS
sortedVolts.sort();
console.log('UNSORTED', volts);
console.log('SORTED', sortedVolts);
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
0

It's happening because of the call by sharing evaluation strategy used by JavaScript. Both variables are pointing to same address in the memory. Create a copy of volts array and then sort it with Array.sort

Nadeem Ahmad
  • 140
  • 1
  • 6