Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent initial array from sorting

I have an array where the order of the objects is important for when I finally output the array in a document. However, I'm also sorting the array in a function to find the highest value. The problem is that I after I run the function to find the highest value, I can't get the original sort order of the array back.

// html document
var data = [75,300,150,500,200];

createGraph(data);

// js document

function createGraph(data) {

    var maxRange = getDataRange(data);

    // simpleEncode() = google encoding function for graph
    var dataSet = simpleEncode(data,maxRange);

}

function getDataRange(dataArray) {
    var num = dataArray.sort(sortNumber);
    return num[0];
}

I've also tried setting data to dataA and dataB and using dataB in the getDataRange function and dataA in the simpleEncode function. Either way, data always end up being sorted from highest to lowest.

like image 521
Choy Avatar asked Sep 01 '26 13:09

Choy


1 Answers

As you've discovered, sorting an array modifies the array in-place.
To prevent that, you need to sort() a separate copy of the array, so that the original array is not affected.

You can copy an array by calling slice():

var num = dataArray.slice().sort(sortNumber);
like image 110
SLaks Avatar answered Sep 04 '26 03:09

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!