Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

sort array without mutating js

// You need to copy the array before you sort it.
// One way with es6:
const sorted = [...arr].sort();

// or use slice() without arguments
const sorted = arr.slice().sort();
Comment

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]
Comment

PREVIOUS NEXT
Code Example
Javascript :: js array contains 
Javascript :: string charat javascript 
Javascript :: what is a promise 
Javascript :: javascript swap images on mouseover 
Javascript :: How do i write a script which generates a random rgb color number. 
Javascript :: jwt strategy 
Javascript :: javascript insertbefore 
Javascript :: redux saga fetch data 
Javascript :: js add to array 
Javascript :: Upload a file using ExpressJS+Multer 
Javascript :: comment in js 
Javascript :: send multipart form data axios with node js 
Javascript :: AngularJS how to use btn-group or radio group in list 
Javascript :: how to import scss file in angular 
Javascript :: disable zoom in app 
Javascript :: javascript function return boolean 
Javascript :: ismobile react 
Javascript :: if else jsx 
Javascript :: how to return argument in javascript 
Javascript :: remove index from array javascript 
Javascript :: postman environment variables 
Javascript :: javascript object type 
Javascript :: array includes javascript 
Javascript :: how to convert decimal to roman in javascript 
Javascript :: math.floor 
Javascript :: learn nodejs 
Javascript :: Factorial Recursion Function in Javascript 
Javascript :: react emoji picker 
Javascript :: node-red Logging events to debug 
Javascript :: jquery ajax download file 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =