toSorted() is a recently released method that creates a copy of the existing array and returns a new array. Unlike the sort() function, toSorted() does not alter the original array.
// sort
const array1 = [ { name: "k", age: 12 } ,{ name: "a", age: 14 }, { name: "b", age: 14 }, { name: "c", age: 13 }, { name: "d", age: 13 }, { name: "e", age: 13 }, { name: "f", age: 13 }, { name: "g", age: 13 }, { name: "h", age: 13 }, { name: "i", age: 12 }, { name: "j", age: 12 }, ]
array1.**sort**( (a,b) => a.age - b.age)
console.error(array1)
output
[
{ name: 'k', age: 12 },
{ name: 'i', age: 12 },
{ name: 'j', age: 12 },
{ name: 'c', age: 13 },
{ name: 'd', age: 13 },
{ name: 'e', age: 13 },
{ name: 'f', age: 13 },
{ name: 'g', age: 13 },
{ name: 'h', age: 13 },
{ name: 'a', age: 14 },
{ name: 'b', age: 14 }
]
Here you can see the original array has not been modified.
I will be posting tricks I have been using in my journey.
So follow me on LinkedIn.
Top comments (0)