NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Sort An Array Without Mutating The Initial Array In JavaScript

July 2022

TL;DR -- p This is how to get a sorted copy of an array without changing the original one in JavaScript -- code/ -- js const initial = ['a', 'c', 'd', 'b']; const new_thing = Array.from(initial).sort(); console.log(initial); console.log(new_thing); -- /code -- results/ [ 'a', 'b', 'c', 'd' ] [ 'a', 'c', 'd', 'b' ] -- /results -- p Details

Calling .sort() directly on an array alters it to have the sorted ordering. For example:

const example = ['a', 'c', 'd', 'b'];

[ 'a', 'c', 'd', 'b' ]
  [ 'a', 'b', 'c', 'd' ]

That's generally what I'm after but there are times when I need the original ordering to stay intact. The code at the top of the post does that by making a new array from the values in the first array and then sorting off that.


- I use this for arrays of strings. Dealing with arrays of object might take more work.

═══ § ═══