Prevent sorting of the initial array

I have an array where the order of the objects is very important when I am finally outputting the array to a document. However, I also sort the array in the function to find the highest value. The problem is, after running the function to find the highest value, I cannot get back the original sort order of the array.

// 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 have also tried setting data to dataA and dataB and using dataB in getDataRange function and dataA in simpleEncode function. In any case, the data always ends up sorted from highest to lowest.

+2


a source to share


4 answers


As you discovered, an sort

array of arrays modifies the array in place.
To prevent this from happening, you need sort()

to create a separate copy of the array so that the original array is not affected.

You can copy the array by calling slice()

:



var num = dataArray.slice().sort(sortNumber);

      

+6


a source


You can find the maximum value of your array simply by applying it Math.max

, you don't need to sort it:



function getDataRange(dataArray) {
  return Math.max.apply(Math, dataArray);
}

      

+5


a source


Instead of sorting the array to get the maximum value, just use a for or foreach loop to go through it and find the highest value. This will be faster than sorting and will leave your array unchanged.

+2


a source


Two possibilities: either sort the copy of the array (as long as it is not too large), or scan through the array to find the largest element without sorting it at all.

0


a source







All Articles