Sorting Numbers for Largest Possible Number in JavaScript

Learned this sorting pattern today. When arranging numbers to form the largest possible number, normal sorting doesn't work. Example: [3, 30, 34, 5, 9] → "9534330" The pattern: [3, 30, 34, 5, 9] .map(String) .sort((a, b) => (b + a) - (a + b)) .join("") How it's different: Regular sort (b - a) compares numeric values This pattern compares concatenations instead For 3 vs 30: "303" vs "330" → "330" wins → 3 comes before 30 Been coding for 2 years, first time using this. Always something new to learn. #javascript #coding

To view or add a comment, sign in

Explore content categories