JS sort works in Firefox but not IE - can't work out why
- by Max Williams
I have a line in a javascript function that sort an array of objects based on the order of another array of strings. This is working in firefox but not in IE and i don't know why. Here's what my data looks like going into the sort call. (I'm using an array of three items just to illustrate the point here).
//cherry first then the rest in alphabetical order
originalData = ['cherry','apple','banana','clementine','nectarine','plum']
//data before sorting - note how clementine is second item - we wan to to to be after apple and banana
csub = [
{"value":"cherry","data":["cherry"],"result":"cherry"},
{"value":"clementine","data":["clementine"],"result":"clementine"},
{"value":"apple","data":["apple"],"result":"apple"},
{"value":"banana","data":["banana"],"result":"banana"},
{"value":"nectarine","data":["nectarine"],"result":"nectarine"},
{"value":"plum","data":["plum"],"result":"plum"}
]
//after sorting, csub has been rearranged but still isn't right: clementine is before banana
csubSorted = [
{"value":"cherry","data":["cherry"],"result":"cherry"},
{"value":"apple","data":["apple"],"result":"apple"},
{"value":"clementine","data":["clementine"],"result":"clementine"},
{"value":"banana","data":["banana"],"result":"banana"},
{"value":"nectarine","data":["nectarine"],"result":"nectarine"},
{"value":"plum","data":["plum"],"result":"plum"}
]
Here's the actual sort code:
csubSorted = csub.sort(function(a,b){ return (originalData.indexOf(a.value) > originalData.indexOf(b.value)); });
Can anyone see why this wouldn't work? Is the basic javascript sort function not cross-browser compatible? Can i do this a different way (eg with jquery) that would be cross-browser?
grateful for any advice - max