I am trying to sort the array elements as below:
let defaultOrder = [
{'item': 'Pen', 'value': '5'},
{'item': 'Spike', 'value': '5'},
{'item': 'Pencil', 'value': '5'},
{'item': 'Ink', 'value': '5'},
{'item': 'Mail', 'value': '5'},
{'item': 'Rubber', 'value': '5'}
];
let items = [
{'item': 'Spike', 'value': '5'},
{'item': 'Duck', 'value': '5'},
{'item': 'Ink', 'value': '5'},
{'item': 'Pencil', 'value': '5'},
{'item': 'Rubber', 'value': '5'},
{'item': 'Mail', 'value': '5'},
{'item': 'Pen', 'value': '5'}
];
let orderedItems = items.sort(function (a,b){
return defaultOrder.indexOf(a.item) - defaultOrder.indexOf(b.item)
});
I am able to sort the elements, but how to make the unsorted elements, from above: {'item': 'Duck', 'value': '5'}
, to get appended at the very end of the sorted items?
4
Answers
You could take an object for the positions and a default value for unknown items.
Check if an item isn’t found in
defaultOrder
, and return an appropriate value so it will sort at the end.The way to do that is to check if exactly one of those is not found in the
defaultOrder
array, then return1
to-1
to signify the order.Additionally, you need to use
Array.prototype.findIndex
to find an object with that property. Originally, you were searching for the string'Pen'
(for example) instead of an object that has the.item
property as'Pen'
You don’t need to use
Array::sort()
since you have already a sorted order in the first array (so use an already known information to your advantagle).