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.
a source to share
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);
a source to share
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);
}
a source to share