Languages

JavaScript - sort array except one element

0 points
Asked by:
Dexter
660

How can I sort all values in array of object by key except one element?

For example, when I have an array:

I want all the values to be sorted by key, except the undefined value, I want it to be at the beginning.

So the result would be:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

You can use sort() method with custom compare function as its argument.

Practical example:

Note:

This function sorts all items using regular sorting, except for items with undefined keys, they are being placed at the beginning.

 

References

  1. Array.prototype.sort() - JavaScript | MDN
0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join