使用数组作为排序顺序

时间:2016-03-01 10:21:02

标签: javascript arrays sorting

我想使用一个字符串数组作为模板,如何订购其他数组。

var sort = ["this","is","my","custom","order"];

然后我想根据该顺序的键(内容)对对象数组进行排序:

var myObjects = [
    {"id":1,"content":"is"},
    {"id":2,"content":"my"},
    {"id":3,"content":"this"},
    {"id":4,"content":"custom"},
    {"id":5,"content":"order"}
];

所以我的结果是:

sortedObject = [
    {"id":3,"content":"this"},        
    {"id":1,"content":"is"},
    {"id":2,"content":"my"},
    {"id":4,"content":"custom"},
    {"id":5,"content":"order"}    
];

我该怎么做?

4 个答案:

答案 0 :(得分:3)

您可以在 sort() indexOf()

的帮助下做同样的事情

var sort = ["this", "is", "my", "custom", "order"];

var myObjects = [{
  "id": 1,
  "content": "is"
}, {
  "id": 2,
  "content": "my"
}, {
  "id": 3,
  "content": "this"
}, {
  "id": 4,
  "content": "custom"
}, {
  "id": 5,
  "content": "order"
}];

var sortedObj = myObjects.sort(function(a, b) {
  return sort.indexOf(a.content) - sort.indexOf(b.content);
});

document.write('<pre>' + JSON.stringify(sortedObj, null, 3) + '</pre>');

答案 1 :(得分:0)

您需要使用.map

var sort = ["this", "is", "my", "custom", "order"];
var myObjects = [{
   "id": 1,
   "content": "is"
}, {
   "id": 2,
   "content": "my"
}, {
   "id": 3,
   "content": "this"
}, {
   "id": 4,
   "content": "custom"
}, {
   "id": 5,
   "content": "order"
}];
var myObjectsSort = sort.map(function(e, i) {
   for (var i = 0; i < myObjects.length; ++i) {
      if (myObjects[i].content == e)
         return myObjects[i];
   }
});
document.write('<pre>' + JSON.stringify(myObjectsSort , null, 3) + '</pre>');

答案 2 :(得分:0)

  

创建一个新数组并放置来自myObjects的每个对象,考虑index

sort

试试这个:

&#13;
&#13;
var sort = ["this", "is", "my", "custom", "order"];
var myObjects = [{
  "id": 1,
  "content": "is"
}, {
  "id": 2,
  "content": "my"
}, {
  "id": 3,
  "content": "this"
}, {
  "id": 4,
  "content": "custom"
}, {
  "id": 5,
  "content": "order"
}];
var newArr = [];
myObjects.forEach(function(item) {
  var index = sort.indexOf(item.content);
  newArr[index] = item;
});
console.log(newArr);
&#13;
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我建议使用一个对象来存储排序顺序。

&#13;
&#13;
var sort = ["this", "is", "my", "custom", "order"],
    sortObj = {},
    myObjects = [{ "id": 1, "content": "is" }, { "id": 2, "content": "my" }, { "id": 3, "content": "this" }, { "id": 4, "content": "custom" }, { "id": 5, "content": "order" }];

sort.forEach(function (a, i) { sortObj[a] = i; });

myObjects.sort(function (a, b) {
    return sortObj[ a.content] - sortObj[ b.content];
});
	
document.write('<pre>' + JSON.stringify(myObjects, 0, 4) + '</pre>');
&#13;
&#13;
&#13;