在Javascript中对数组进行分组和排序

时间:2017-09-07 11:45:44

标签: javascript angularjs arrays

我有以下变量:

var myArray = [
  {name: "Alf", "type": "Phone"},
  {name: "John", "type": "Web"},
  {name: "Peter", "type": "Email"},
  {name: "Louise", "type": "Phone"},
  {name: "Jenny", "type": "Email"},
  {name: "Fred", "type": "Web"}
]

我想按类型和特定顺序对其进行分组:首先是所有" Web",然后是所有"电子邮件",然后是所有"电话&# 34;,如下:

  {name: "John", "type": "Web"},
  {name: "Fred", "type": "Web"},
  {name: "Peter", "type": "Email"},
  {name: "Jenny", "type": "Email"},
  {name: "Louise", "type": "Phone"},
  {name: "Alf", "type": "Phone"},

我尝试了下面的代码,它将它们分组但没有订单。

var grouped = _(myArray)
          .groupBy('type')
          .flatten()
          .value();

如何根据需要订购这些群组?

3 个答案:

答案 0 :(得分:1)

您可以使用标准Array#sort。但是,由于您需要特定对象,因此您需要为每种类型分配值,然后使用排序中的值:



/** assign a value for each type **/
var order = {
  "Web": 300,
  "Email": 200,
  "Phone": 100
};

var myArray = [
  {name: "Alf", "type": "Phone"},
  {name: "John", "type": "Web"},
  {name: "Peter", "type": "Email"},
  {name: "Louise", "type": "Phone"},
  {name: "Jenny", "type": "Email"},
  {name: "Fred", "type": "Web"}
];

myArray.sort(function(a, b) {
  // sort using the values
  return order[b.type] - order[a.type];
});

console.log(myArray);




答案 1 :(得分:1)

您可以使用JavaScript的Array.sort()函数,以及包含值权重的特定地图:



var myArray = [
  {name: "Alf", "type": "Phone"},
  {name: "John", "type": "Web"},
  {name: "Peter", "type": "Email"},
  {name: "Louise", "type": "Phone"},
  {name: "Jenny", "type": "Email"},
  {name: "Fred", "type": "Web"}
];
// could be any three primitives as long as p1 < p2 < p3, i.e: 'a', 'k', 'z'
var myMap = {"Web":0, "Email":1, "Phone":2};
myArray.sort(function(a, b) {
	return myMap[a.type] - myMap[b.type]; // sort by weights
});
console.log(myArray);
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用排序顺序的对象和类型的默认值进行排序,这些类型没有已知的顺序。

&#13;
&#13;
var array = [{ name: "last", type: "very last" }, { name: "Alf", type: "Phone" }, { name: "John", type: "Web" }, { name: "Peter", type: "Email" }, { name: "Louise", type: "Phone" }, { name: "Jenny", type: "Email" }, { name: "Fred", type: "Web" }],
    order = { Web: 1, Email: 2, Phone: 3 };

array.sort(function (a, b) {
    return (order[a.type] || Infinity) - (order[b.type] || Infinity);
});

console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;