Sort numbers in JavaScript and keep the original array

Sort numbers in JavaScript and keep the original array

Calling sort() on numbers can put 10 before 2. JavaScript’s default array sort does not simply compare numeric magnitude. Supply a comparator when you want a numeric ordering, and decide whether changing the original array is acceptable.

The examples use arrays of finite numbers and can run in a browser console or Node.js. The last example needs an environment that supports toSorted().


Sort numbers in ascending order

const values = [2, 10, 1];
console.log(values.sort());

The result is ordered as [1, 10, 2]. With no comparator, elements are compared as strings, which can differ from their numeric order.

const values = [2, 10, 1];
console.log(values.sort((a, b) => a - b));

The comparator produces [1, 2, 10]. A negative result places a before b, a positive result places it after b, and zero treats them as equal for ordering. Returning only a > b does not express the full comparison because it never supplies a negative result.

Reverse the numeric order

const values = [2, 10, 1];
console.log(values.sort((a, b) => b - a));

Subtracting in the opposite direction gives [10, 2, 1]. The important part of the returned value is its sign, not its exact magnitude.

Preserve the original array

sort() mutates the array it is called on. To keep the input order available, copy first and sort that new array.

const original = [2, 10, 1];
const sorted = [...original].sort((a, b) => a - b);
console.log(JSON.stringify(original));
console.log(JSON.stringify(sorted));
console.log(original === sorted);
[2,10,1]
[1,2,10]
false

Spread syntax creates a different array, so the original order remains unchanged. This is a shallow copy: if the elements are objects, both arrays still refer to those same objects. Reordering the copy does not clone their properties.

Sort objects by a numeric property

const rows = [
  { name: "alpha", score: 20 },
  { name: "beta", score: 3 }
];
const ordered = [...rows].sort((a, b) => a.score - b.score);
console.log(ordered.map(row => row.name).join(","));

The output is beta,alpha, following ascending score. Check the input before using this comparator if a property can be missing, a string or NaN. Decide how those cases should be ordered rather than assuming subtraction defines a useful order for every input.

Use toSorted when supported

const values = [2, 10, 1];
const sorted = values.toSorted((a, b) => a - b);
console.log(JSON.stringify(values));
console.log(JSON.stringify(sorted));

The original remains [2,10,1], and the new array is [1,2,10]. toSorted() returns a sorted copy directly. Check support in the browsers or Node.js versions you need to run; older environments can use the spread-and-sort form shown earlier.

Numeric strings and human-language names need their own input and comparison decisions. Start by checking the element types, choosing ascending or descending order, and deciding whether the caller should see its input array changed. Those choices determine which example fits the task.

References

このブラウザからの自分のアクセスを解析から除外できます。