I am trying to sort an array of objects that looks like so –
const originalArray = [
{ name: 'Blue', id: '123', category: 'none' },
{ name: 'Red', id: '145', category: 'none' },
{ name: 'Pink', id: '589', category: 'none' },
{ name: 'Orange', id: '267', category: 'none' },
{ name: 'Green', id: '781', category: 'none' },
]
I have another array which is my ‘sort order’ –
const sortList = [ 'Green', 'Pink', 'Blue' ]
The sort order I have does not include all of the items in the original array. I am trying to do this –
const sortedArray = originalArray.sort(function (a, b) {
return sortList.indexOf(a.name) - sortList.indexOf(b.name);
});
However when I console.log the sortedArray, it is exactly the same as the original array. I’m not sure what I’m doing wrong. Ideally, I would like the array to be sorted and the ones not included in the sortList should just be at the end. Like so –
const sortedArray = [
{ name: 'Green', id: '781', category: 'none' },
{ name: 'Pink', id: '589', category: 'none' },
{ name: 'Blue', id: '123', category: 'none' },
{ name: 'Red', id: '145', category: 'none' },
{ name: 'Orange', id: '267', category: 'none' },
]
3
Answers
If an item is not found
-1
is returned, you have to handle that caseThe above code first separates the items into two arrays,
inSortList
andnotInSortList
. Then, it sortsinSortList
based on the order defined insortList
and finally concatenates the two arrays to get the desired sorted result.Your original code worked, but it put the unknown values first (red and orange).
I modified your code a bit and it now works: