• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Inserting Object Into Array Alphabetically From Nested Key Value

Resolved: Inserting Object Into Array Alphabetically From Nested Key Value

0
By Isaac Tonny on 16/03/2023 Issue
Share
Facebook Twitter LinkedIn

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:
The last item is: { enabled: false, id: “dscjidovvocsi”, name: “Pear” }
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:
For example:
FYI: I debugged this with this snippet in the loop:
Which made it pretty clear what was going on when it logged this:
debug results

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com

javascript lodash typescript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: EntityFramework creates/runs migrations using parameterless DataContext instance

24/03/2023

Resolved: Visual Studio 2022 crashes when using breakpoints

24/03/2023

Resolved: How to get Union type from an array of objects in Flow?

24/03/2023

Comments are closed.

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.