使用数组作为排序顺序
Use array as sort order
我想使用字符串数组作为模板如何对其他数组进行排序。
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>');
相关文章:
- 2个backbone.js集合,具有相同的模型,但排序顺序不同
- 如何使用下划线根据自定义排序顺序对对象数组进行排序
- 如何根据不同排序顺序的多个值对json对象进行排序
- 如何使用Jquery Data表更正排序顺序
- 使用Async.js sortBy的升序与降序排序顺序
- 如何在Jquery中使用给定的任何特定排序顺序对字符串数组进行排序
- JavaScript 排序顺序错误
- 如何在 select2() 字段中保存排序顺序
- Jquery DataTable 组排序顺序
- 按可排序顺序获取所有文本区域内容
- 是否可以按当前排序顺序获取跨多个页面的所有 jqGrid 行
- 使用数组作为排序顺序
- 如何将其转换为排序顺序
- 打开 Graph API 排序顺序,或简单的 jQuery/JavaScript 排序
- 谷歌地图 API - 最近的点 - 更改排序顺序
- 如何保存排序顺序
- 反转角度中的排序顺序
- 迭代 JavaScript 集合并添加排序顺序
- 根据数字排序顺序更新自动重新排列HTML列表
- 在backbone.js中,如何使用新的模型数据更新视图,同时在没有完整渲染的情况下保持排序顺序