DEV Community

Discussion on: Learn Javascript array methods with the help of emojis

Collapse
 
vetrivel profile image
Vetrivel p

let arr = [0,1,2,3,4,5,6,7,8,9,10] - Input

let arr = [10,1,2,3,4,5,6,7,8,9,0] - output

Please explain how to rearrange.

Collapse
 
sakethkowtha profile image
sakethk • Edited
let arr = [0,1,2,3,4,5,6,7,8,9,10]

const swap = (list, x, y) =>  [ arr[x], arr[y] ] = [ arr[y], arr[x] ];


arr.sort((a, b) =>  a - b)
swap(arr, 0, arr.length - 1)
console.log(arr) //[10,1,2,3,4,5,6,7,8,9,0]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vetrivel profile image
Vetrivel p • Edited

Thank you so much!
I am beginner in javaScript, If possible can you expalin the code.

Thread Thread
 
sakethkowtha profile image
sakethk

We are sorting the array in ascending order after ascend ascending the array will be like this [0,1,2,3,4,5,6,7,8,9,10]. Later we need to swap first and last element in the array

Thread Thread
 
vetrivel profile image
Vetrivel p

ok, noted thank you so much.