Skip to content
The Chat Archive
o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K

how to sort an array oh numbers in JS?

  1. User

    how to sort an array oh numbers in JS?

  2. Assistant

    To sort an array of numbers in JavaScript you’ll want to use the built‑in sort() method with a numeric comparator. By default, sort() converts items to strings and compares lexicographically (“1”, “10”, “2”, …), so you need to tell it how to compare two numbers.

    const nums = [10, 5, 2, 30, 100];
    
    // Ascending order
    nums.sort((a, b) => a - b);
    console.log(nums);  // [2, 5, 10, 30, 100]
    
    // Descending order
    nums.sort((a, b) => b - a);
    console.log(nums);  // [100, 30, 10, 5, 2]
    

    Explanation of the comparator (a, b) => a - b:

    • If a - b is negative, a comes before b
    • If a - b is positive, b comes before a
    • If a - b is zero, their order stays the same (stable sort)

    Tip: sort() mutates the original array. If you need to keep the original intact, first make a copy:

    const original = [3, 1, 4, 1, 5];
    const sorted   = [...original].sort((a, b) => a - b);
    
    console.log(original); // [3, 1, 4, 1, 5]
    console.log(sorted);   // [1, 1, 3, 4, 5]
    

    That’s it! Let me know if you need examples of custom sorting or more advanced techniques. 😊

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.