1

I have an array of indexes, called indexSelected. There is also an array of objects called weather. I have put all of the Site Names that that I am dealing with into an array called stationName. I want to sort this array alphabetically whilst keeping the original indexes for that I can refer back to the other properties associated with object. I have tried the method below, however, I cannot seem to get it to work.

var stationName=[];
for (var i=0; i<indexSelected.length; i++) {
    stationName.push(weather[indexSelected[i]]["Site Name"]);    
}

var copyStationName = stationName.slice(0)
var sortedStationName = stationName.sort();
var originalIndex=[];
for (var i=0; i<stationName.length; i++) {
   originalIndex.push(copyStationName.indexOf(sortedStationName[i]))
}

var station=[];
for (var i=0; i<indexSelected.length; i++) {
    station.push(weather[originalIndex[i]]["Site Name"]);
}

This station array was to check that the originalIndexes array was correct. It isn't, and I don't know why. I would appreciate some help, or another way to sort this array. I'm looking to put all of the data into a table, sort alphabetically by site name. Thanks

2
  • 1
    provide a demo in jsfiddle.net , a lot easier to troubleshoot when data visible and can use browser console for debugging Commented Nov 13, 2013 at 19:50
  • This sounds like asort() in PHP. There's a JS version of that here. Commented Nov 13, 2013 at 19:55

1 Answer 1

3

Build an array of objects that carry both the name and index, then use a custom comparison function for the sort. E.g.

var stationInfo = [];
for (var i=0; i<indexSelected.length; i++) {
  var idx = indexSelected[i];
  stationInfo.push({name: weather[idx]["Site Name"], idx: idx);    
}

stationInfo.sort(function(a, b) {
  // a & b are the array items (info objects) created above, so make 'em
  // point at the `name` property we want to sort by
  a = a.name;
  b = b.name;
  // ... then return -1/0/1 to reflect relative ordering
  return a < b ? -1 : (a > b ? 1 : 0);
})

// output a name + index pair
console.log(stationInfo[0].name, stationInfo[0].idx);
Sign up to request clarification or add additional context in comments.

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.