按字母和数字降序排列对象数组

时间:2018-03-19 14:15:43

标签: javascript

data = [{"map_name": "PHX7260.AE5020003.9"}, 
        {"map_name": "PHX7260.AE5020003.10"}, 
        {"map_name": "PHX7260.AE5020003.1"}]

我想按字母顺序和数字顺序按降序对这些数据进行排序。

我尝试了以下但它不适用于对象数组。

var myArray  = data;
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
console.log(myArray.sort(collator.compare));

我应该如何处理它,接收对象的数据,它应该仅作为对象返回,而不是作为要显示的数组返回。

3 个答案:

答案 0 :(得分:1)

array#sort string#localeCompare numerictrue属性设置为const data = [{"map_name": "PHX7260.AE5020003.9"}, {"map_name": "PHX7260.AE5020003.10"},{"map_name": "PHX7260.AE5020003.1"}]; data.sort((a,b) => b.map_name.localeCompare(a.map_name, undefined, {numeric: true})); console.log(data);



header('Location: /A.html');




答案 1 :(得分:0)

  • 您可以分别获取最后一个点之前/之后的字符串和数字。

  • 首先比较字符串,如果它们按数字排序,则使用函数localeCompare

此方法使用降序进行排序。

了解ZHX7260.AE5020003.10如何放置在第一个位置。

var data = [{"map_name": "PHX7260.AE5020003.9"},        {"map_name": "ZHX7260.AE5020003.10"},        {"map_name": "PHX7260.AE5020003.10"},        {"map_name": "PHX7260.AE5020003.1"}];
        
data.sort((a, b) => {
  var astr = a.map_name.substring(0, a.map_name.lastIndexOf('.'));
  var bstr = b.map_name.substring(0, b.map_name.lastIndexOf('.'));
  
  if (astr === bstr) {
    var aidx = a.map_name.substring(a.map_name.lastIndexOf('.') + 1);
    var bidx = b.map_name.substring(b.map_name.lastIndexOf('.') + 1);
    
    return bidx - aidx;
  } else return bstr.localeCompare(astr);
}); 

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
also since PHX7260.AE5020003 are same hence the output expected is above , if the string aredifferent it should sort the string first and then the number

答案 2 :(得分:0)

使用javascript的原生Array.sort()方法,您可以在.上拆分字符串并执行如下所示的多步骤排序:



var data = [{"map_name": "PHX7260.AE5020003.9"}, 
        {"map_name": "PHX7260.AE5020003.10"}, 
        {"map_name": "PHX7260.AE5020003.1"}]
    
function compare(a,b){
  if(!!parseInt(a) && !!parseInt(b)){
    a = parseInt(a)
    b = parseInt(b)
  }
  if(a > b) return 1
  else if(a < b) return -1
  else return 0
}
    
function sortData(a,b){
  let a_arr = a.map_name.split('.'),
    b_arr = b.map_name.split('.')
    
  while(a_arr.length){
    let val = compare(a_arr.shift(), b_arr.shift())
    if(val) return val
  }
  
  return 0
}

console.log(data.sort(sortData))
&#13;
&#13;
&#13;