使用数组作为排序顺序 [英] Use array as sort order
本文介绍了使用数组作为排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用字符串数组作为模板,如何对其他数组进行排序.
I want to use an array of strings as template how to order other arrays.
var sort = ["this","is","my","custom","order"];
然后我想按键(内容)的顺序对对象数组进行排序:
and then i want to sort an array of objects depending on a key (content) by that 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"}
];
我该怎么做?
推荐答案
您可以在 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>');
这篇关于使用数组作为排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文