Languages

JavaScript - does sort method modify original array?

0 points
Asked by:
Walter
586

Does sort() method modify the original array?

I have the following piece of code:

Should I redefine array or is it possible to just call sort() like presented below?

Will the sort() method change the original array?

1 answer
0 points
Answered by:
Admin Dirask Community
4380

The filter() method itself does mutate the original array. You can use slice() method to create copyt of the original array and then sort it.

Practical example:

Note:

Notice that you should use a.id - b.id instead of a.id > b.id to sort an array.

 

References

  1. Array.prototype.filter() - 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