繁体   English   中英

排序数组但保留原始索引

[英]Sorting Array but keeping Original Index

我有一个索引数组,称为indexSelected。 还有一系列称为天气的对象。 我已将要处理的所有站点名称放入名为stationName的数组中。 我想按字母顺序对数组进行排序,同时保留原始索引,以便可以引用与对象关联的其他属性。 我尝试了下面的方法,但是,我似乎无法使它起作用。

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"]);
}

该工作站数组用于检查originalIndexes数组是否正确。 不是,我也不知道为什么。 我希望获得一些帮助,或以其他方式对该数组进行排序。 我希望将所有数据放入表中,并按站点名称的字母顺序排序。 谢谢

构建一个同时包含名称和索引的对象数组,然后使用自定义比较功能进行排序。 例如

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM