【发布时间】:2019-12-04 14:33:09
【问题描述】:
我有一个这样的对象数组,想用另一个对象数组重新排序。我曾尝试使用 indexOf 但可能会混淆我的语法,因为数组无法重新排序。我已经阅读了类似的问题,但无法将这些解决方案应用于我的问题。这是代码:
const task = [
{'title':1.1 , 'description': 'task description here' },
{'title':1.2 , 'description': 'task description here' },
{'title':1.3 , 'description': 'task description here' },
{'title':1.4 , 'description': 'task description here' }
];
var taskSort = [
{'title':1.2 },
{'title':1.4 },
{'title':1.3 },
{'title':1.1 }
];
task.sort(function(a, b) {
return taskSort.indexOf(a.title) - taskSort.indexOf(b.title); \\have tried many variations of this line
});
console.clear();
console.log(task);
非常感谢!
【问题讨论】:
-
您希望它们如何排序?什么条件?
-
您正在搜索
taskSort中不存在的元素。尝试做taskSort.map(o => o.title).index(a.title),这将返回正确的索引。当然,将taskSort.map(o => o.title)保存在一个变量中,这样您就不会一次又一次地执行map操作。
标签: javascript arrays sorting object