我有一个数组,我想根据另一个数组进行排序。如果两个数组的长度相同,则下面的代码可以正常工作。但是,如果我的名为 order
的数组缺少一个元素,我仍然想在新排序数组的末尾显示该元素。这是一个简单的例子:
//Source arrays
var order = [{_id: '123', type: '2'},{_id: '123', type: '1'}];
var elements = [{_id: '124', type: '1', name: '(should be last, not sorted)'},{_id: '123', type: '1', name: 'second(should be second)'},{_id: '123', type: '2', name: 'third(should be first)'}];
var sorted = [];
for (var i = 0, len = order.length; i < len; i++) {
var element = elements.filter(function (el) {
return el.type == order[i]['type'] &&
el._id == order[i]['_id'];
});
sorted.push(element[0]);
}
//Just for testing
var list = document.createElement('ul');
for (var i = 0, len = sorted.length; i < len; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(sorted[i]['name']));
list.appendChild(item);
}
document.getElementById('list').appendChild(list);
<div id="list"></div>
如您所见,现在我的排序数组中只有两项。如何在末尾添加 elements
中缺少的项目?
最佳答案
您可以使用array.findIndex
来获取索引,然后进行相应的排序
var order = [{_id: '123', type: '2'},{_id: '123', type: '1'}];
var elements = [{_id: '124', type: '1', name: '(should be last, not sorted)'},{_id: '123', type: '1', name: 'second(should be second)'},{_id: '123', type: '2', name: 'third(should be first)'}];
elements.sort(function(a, b) {
var MAX_VALUE = 9999999;
var index_a = order.findIndex(function(el) {
return el._id === a._id && el.type === a.type;
});
var index_b = order.findIndex(function(el) {
return el._id === b._id && el.type === b.type;
});
index_a = index_a < 0? MAX_VALUE : index_a;
index_b = index_b < 0? MAX_VALUE : index_b;
return index_a > index_b ? 1 : index_a < index_b ? -1 : 0
});
console.log(elements)
关于javascript - 在 JavaScript 中根据另一个数组对数组进行排序,同时将未排序的元素保留在末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39788264/