如何基于重复值angularjs对数组进行排序

时间:2018-02-22 11:50:02

标签: javascript jquery html angularjs

我有以下数据

  var data = [
   {
    "h_id"  : "31",
    "city": "hill",       
}, {
    "h_id": "4",
    "city": "Bevery Hills",     
}, {
    "h_id": "5",
    "city": "New York",    
}, {
    "h_id": "31",
    "city": "New York",   
}, {
    "h_id": "5",
    "city": "New York",   
}
];

我希望数据按“id”顺序排序,如下所示

  var data = [
   {
    "h_id"  : "31",
    "city": "hill",       
}, {
    "h_id": "31",
    "city": "Bevery Hills",     
}, {
    "h_id": "4",
    "city": "New York",    
}, {
    "h_id": "5",
    "city": "New York",   
}, {
    "h_id": "5",
    "city": "New York",   
}
];

如何根据上面的场景创建一个过滤id值的函数

4 个答案:

答案 0 :(得分:2)

您可以将自定义函数传递给JavaScript的sort方法:

var data = [{
  "h_id": "31",
  "city": "hill",
}, {
  "h_id": "4",
  "city": "Bevery Hills",
}, {
  "h_id": "5",
  "city": "New York",
}, {
  "h_id": "31",
  "city": "New York",
}, {
  "h_id": "5",
  "city": "New York",
}];

var result = data.sort(function(a, b) {
  return a.h_id.localeCompare(b.h_id);
});

console.log(result);

答案 1 :(得分:0)

您只需要使用比较器函数在数组上调用<img id="cf" class="bottom" src="photos/800_800_<?php echo $r->image1;?>" /> 方法。

&#13;
&#13;
.sort
&#13;
&#13;
&#13;

答案 2 :(得分:0)

sort()方法对数组中的元素进行排序并返回数组。阅读更多相关信息here

这就是你完成任务的方式

&#13;
&#13;
var data = [
   {
    "h_id"  : "31",
    "city": "hill",       
}, {
    "h_id": "4",
    "city": "Bevery Hills",     
}, {
    "h_id": "5",
    "city": "New York",    
}, {
    "h_id": "31",
    "city": "New York",   
}, {
    "h_id": "5",
    "city": "New York",   
}
];
  data.sort(function (a, b) {
          return parseInt(b.h_id) - parseInt(a.h_id);
     });
     
     console.log(data)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您希望按字符串(而非数字)排序,因此根据Array sort docs您应该执行以下操作;

&#13;
&#13;
var data = [
   {
    "h_id"  : "31",
    "city": "hill",       
}, {
    "h_id": "4",
    "city": "Bevery Hills",     
}, {
    "h_id": "5",
    "city": "New York",    
}, {
    "h_id": "31",
    "city": "New York",   
}, {
    "h_id": "5",
    "city": "New York",   
}
];

data.sort(function(a, b) {
  if (a.h_id < b.h_id) {
    return -1;
  }
  if (a.h_id > b.h_id) {
    return 1;
  }
  return 0;
});

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