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
🚀 Join Zyntiq – Unleash Your Potential! Ready to launch your career and gain real corporate experience? Zyntiq is inviting applications for paid remote internships in *Talent Acquisition, Sales And Marketing Role.* *Why Choose Zyntiq?* ⏱️Mode: Remote 📆Duration: 2 Months that could change your life (and can be extended!) 🕰️Flexible hours, work from anywhere 🎯Maximum learning, zero boredom 📚Exciting hands-on projects *About the company:* Zyntiq is an international and national AI-based digital learning platform offering trending and in-demand courses focused on artificial intelligence. It equips learners with practical skills and industry insights to excel in high-growth tech careers and seize new job opportunities. *Get Rewarded Like a Pro!* • Internship Completion Certificate • Letter of Recommendation • Pre-Placement Offer (WFH) • Additional Skill Certificates • Performance-Based Stipend upto 10k • Daily Incentives *Who can apply?* • Students and freshers with drive • Anyone hungry for real work DM: 6392496753