I have an array that i want to sort based on another array. If both array is the same length, the code below works fine. However, if my array called order is missing an element, i still want to display that at the end of the new sorted array. Here is a quick example:
//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>
As you can see, now i only have two items in my sorted array. How can i add the missing item(s) from elements at the end?