3

barValues is an array I'm passing to a function. Within the function I have this:

alert(barValues);

var sortedBarValues = barValues;
sortedBarValues.sort(function(a,b){return b - a});

alert(barValues);

I'm trying to end up with two arrays. barValues being the original array and sortedBarValues being a copy of that array, now sorted.

However, via the two alerts, I'm finding that barValues is ALSO being sorted. Why is that? What is the proper way to make a copy of an array so sort it separately from the original array?

DA.
  • 39,848
  • 49
  • 150
  • 213

3 Answers3

7

With the statement var sortedBarValues = barValues;, you are not making a copy of the array. You are only making a reference. Both names refer to the same array.

You can copy it with var sortedBarValues = barValues.slice();. The slice method is meant for slicing arrays, but if you don't pass any parameters to it, it will make a copy.

Keep in mind that using the slice method won't work properly on multi-dimensional arrays. Copying multi-dimensional arrays is somewhat tricky, but jQuery's extend function can do it for you.

You can see information on how to copy an array in this post.

Community
  • 1
  • 1
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
1

When you assigned barValues to sortedBarValues you actually assigned a reference to the original Array. When you sort sortedBarValues, barValues gets sorted as well because they are actually the exact same thing.

You need to make a copy of your array before sorting it, so the other is left unaffected.

var sortedBarValues = Array.apply({}, barValues);
sortedBarValues.sort(function(a, b) { return b - a; });
Alex Barrett
  • 16,175
  • 3
  • 52
  • 51
0
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
var points = [78, 78,99, 2, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
    var len = arr.length
    var min = Infinity;
    while (len--) {
      if (arr[len] < min) {
        min = arr[len];
      }
    }
    return min;
}
</script>

</body>
</html>

Output is 2

Keshav Gera
  • 10,807
  • 1
  • 75
  • 53