使用数组作为排序顺序

Use array as sort order

本文关键字:排序 顺序 数组      更新时间:2023-09-26

我想使用字符串数组作为模板如何对其他数组进行排序。

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

我该怎么做?

你可以在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>');

你需要使用.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>');

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

试试这个:

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);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

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

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