0

Given the following situation:

let ary = [1, 2, 3];

console.dir(ary);
// ^ this console.dir outputs the reversed order, even though ary is not defined using a sort
// 3, 2, 1

function x(ary) {
  let ary2 = ary.sort( function(a,b) { return b-a } );
  // only define ary2 as the sorted array
  return ary2;  
}

document.getElementById('locationAry2').innerHTML = x(ary);
// ^ this is correct since ary2 is reversed in function x
<p id="locationAry2"></p>

Why does it return the array in the variable 'ary' sorted, when only the ary2 is sorted?

Remi
  • 4,663
  • 11
  • 49
  • 84

1 Answers1

2

Array.prototype.sort modifies the original array. You would need to clone ary into ary2 and then sort ary2.

dislick
  • 667
  • 1
  • 7
  • 25
  • I understand. Do you have more information regarding the cloning of objects? Using the [new object method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties#Objects_and_properties) based on this the first array (ary)? – Remi Aug 09 '18 at 12:24
  • 1
    Sure, check out this answer: https://stackoverflow.com/a/20547803/1309907 – dislick Aug 09 '18 at 12:27