Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to sort array numbers in javascript without mutating original array.

// how to sort array numbers in javascript without mutating original array.
// Method 1 using slice() 
const numbers = [100, 25, 1, 5];
const sorted = numbers.slice().sort((a, b) =>  a - b); // returns a new sorted array

console.log(numbers); // [100, 25, 1, 5]
console.log(sorted); // [1, 5, 25, 100]

// Method 2 using spread opertor [...array] 
const numbers = [100, 25, 1, 5];
const sorted = [...numbers].sort((a, b) =>  a - b); // returns a new sorted array

console.log(numbers); // [100, 25, 1, 5]
console.log(sorted); // [1, 5, 25, 100]
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #sort #array #numbers #javascript #mutating #original
ADD COMMENT
Topic
Name
9+1 =