3

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.

1
  • Any of the answers posted so far will solve your problem. Commented Apr 26, 2010 at 15:26

4 Answers 4

9

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);
Sign up to request clarification or add additional context in comments.

Comments

5

You can find the highest value of your array simply by applying the Math.max method to it, you don't need to sort it:

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

2 Comments

You're welcome @George, try it out, IMO apply can be faster than sorting a copy of your original array.
I just tried this method and it works great. My array contains only 6 objects, so I don't see any speed difference, but will definitely keep it in mind in the future.
2

Rather than sorting the array to get the highest value, just use a for or foreach loop to walk through it and find the highest value. It will be faster than sorting, and will leave your array unchanged.

Comments

0

Two possibilities: either sort a copy of the array (fine as long as it's not too big) or else scan through the array to find the largest item without sorting it at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.