JavaScript Array sort method basics

Do you know how the JavaScript Array sort method works? There are two things you need to keep in mind when using the array sort method. ✅ The array sort method does not return a new sorted array but it changes the original array ✅ The array sort method by default sorts numbers array as strings Take a look at the below code: const numbers = [20, 55, 45, 30, 95 ]; const sorted = numbers.sort(); console.log(sorted); // [20, 30, 45, 55, 95] console.log(numbers); // [20, 30, 45, 55, 95] As you can see, the sort method changes the original array and returns a reference of the sorted array which we're storing in the 𝘀𝗼𝗿𝘁𝗲𝗱 variable. so numbers and sorted will print the same result. Now, take a look at the below code: const numbers = [100, 25, 1, 5 ]; numbers.sort(); console.log(numbers); what do you think the output of the above code will be? it's not [1, 5, 25, 100] but it's [1, 100, 25, 5] This is because when sorting numbers, each number is converted to a string. The sort method compares character by character, so the "1" in "100" is smaller than the "2" in "25" so while sorting in ascending order, 100 comes before 25. Sorting an array of objects is also a popular interview question. 𝗖𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗮𝗿𝘁𝗶𝗰𝗹𝗲 𝗹𝗶𝗻𝗸 𝗶𝗻 𝘁𝗵𝗲 𝗰𝗼𝗺𝗺𝗲𝗻𝘁 𝘁𝗼 𝗹𝗲𝗮𝗿𝗻 𝗵𝗼𝘄 𝘁𝗼 𝗳𝗶𝘅 𝘁𝗵𝗲 𝗮𝗯𝗼𝘃𝗲 𝗶𝘀𝘀𝘂𝗲𝘀 𝗮𝗻𝗱 𝗮𝗹𝘀𝗼 𝗲𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴 𝗮𝗯𝗼𝘂𝘁 𝘀𝗼𝗿𝘁𝗶𝗻𝗴 𝗻𝘂𝗺𝗯𝗲𝗿𝘀, 𝗮𝗿𝗿𝗮𝘆𝘀, 𝗮𝗿𝗿𝗮𝘆 𝗼𝗳 𝗼𝗯𝗷𝗲𝗰𝘁𝘀 𝗲𝘁𝗰. 𝘍𝘰𝘳 𝘮𝘰𝘳𝘦 𝘴𝘶𝘤𝘩 𝘶𝘴𝘦𝘧𝘶𝘭 𝘤𝘰𝘯𝘵𝘦𝘯𝘵, 𝘥𝘰𝘯'𝘵 𝘧𝘰𝘳𝘨𝘦𝘵 𝘵𝘰 𝘧𝘰𝘭𝘭𝘰𝘸 𝘮𝘦. #javascript #reactjs #nextjs #webdevelopment

To view or add a comment, sign in

Explore content categories