In this post, we will see how to resolve Inserting Object Into Array Alphabetically From Nested Key Value
Question:
My app makes a http call and returns an array of objects. I need to loop over the objects and insert in to a new array in alphabetical order. Problem is the last item in the newly created array is the only item out of order.Example code: https://stackblitz.com/edit/typescript-zh16xc?file=package.json,index.ts
Aware i can use the native .sort(), however i am opting to forEach because i am performing more operations on each item, but the example has been trimmed down.
Code:
Which is incorrect, all other items are ordered as expected.
Best Answer:
findIndex
will return -1
if can’t find a match.When
-1
is passed as an index to splice
, it inserts that in the second to last place, since negative indices count from the end, rather than the start.So you can fix it by detecting that case and making sure to insert it at the end instead with:

If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com