JavaScript Array

Array.prototype.sort, toSorted, map, and filter, including in-place mutation, default lexicographic sorting, and sparse arrays.

Array is an ECMAScript built-in. It is not a DOM collection such as NodeList, and it is not a Node.js-only type.

Some methods change the existing array. Others return a new array and leave the original alone. That difference matters when you later compare two lists as text.

Examples were checked in Node.js 22, which implements these ECMAScript built-ins. See the MDN documentation for the complete API.

JavaScript tutorial and API overview →

API index

APISummary
Array.prototype.sortSort the array in place. The default comparison uses string conversion, not numeric value.
Array.prototype.toSortedReturn a new sorted array without modifying the original. The comparison rules are the same as sort(), including the default lexicographic order.
Compare two lists after a stable sortTwo arrays that contain the same values in a different order are not equal as JSON text until you sort them first. Use a copy, or toSorted(), so the originals stay intact.
Array.prototype.map and filterfilter() keeps entries for which the callback returns a truthy value. map() builds a new array of callback results. Both leave the original array’s length and slots alone, but they reuse object references.
Sparse arrays and mapEmpty slots are not visited by map(), but they still occupy a position. join() leaves those positions empty; JSON.stringify writes null.

sort and toSorted

Array.prototype.sort() sorts the array in place and returns the same array. If you omit compareFn, each element is converted to a string and compared in lexicographic order. That is why [10, 2, 1] becomes [1, 10, 2], not [1, 2, 10].

Array.prototype.toSorted() returns a new sorted array and leaves the original unchanged. It is an ECMAScript 2023 method and is available in Node.js 20 and later. In older engines, copy the array first and then call sort().

Array.prototype.sort

array.sort(compareFn)

Sort the array in place. The default comparison uses string conversion, not numeric value.

ParameterDescription
compareFnOptional comparator. Return a negative number if a should come before b, a positive number if a should come after b, and 0 if they are equal. If omitted, elements are compared as strings.

Returns: The same array object, now reordered.

Throws

  • TypeError — Thrown if compareFn is provided and is not callable.
  • sort() mutates the original array. Keep a copy if you still need the earlier order.
  • The default string order is rarely what you want for numbers or for ISO dates that are not zero-padded consistently.
javascript
const nums = [10, 2, 1];
console.log(JSON.stringify([...nums].sort()));
console.log(JSON.stringify([...nums].sort((a, b) => a - b)));
const original = [3, 1, 2];
const same = original.sort((a, b) => a - b);
console.log(JSON.stringify(original), same === original);

Expected output

[1,10,2]
[1,2,10]
[1,2,3] true

Related: toSorted

MDN documentation →

Array.prototype.toSorted

array.toSorted(compareFn)

Return a new sorted array without modifying the original. The comparison rules are the same as sort(), including the default lexicographic order.

ParameterDescription
compareFnThe same optional comparator accepted by sort().

Returns: A new array.

  • If toSorted is missing, use [...array].sort(compareFn) or array.slice().sort(compareFn). That copy-then-sort pattern works in older engines.
  • toSorted is not a drop-in replacement for a numeric sort; you still need a compare function for numbers.
javascript
const source = [3, 1, 2];
const copy = source.toSorted((a, b) => a - b);
console.log(JSON.stringify(copy));
console.log(JSON.stringify(source));

Expected output

[1,2,3]
[3,1,2]

Related: sort

MDN documentation →

Compare two lists after a stable sort

JSON.stringify(array.toSorted())

Two arrays that contain the same values in a different order are not equal as JSON text until you sort them first. Use a copy, or toSorted(), so the originals stay intact.

  • This compares values after JSON serialization. It is not a deep-equal function for objects, Dates, or undefined entries.
  • If the items are numbers, pass a numeric compare function to toSorted().
javascript
const before = ["pear", "apple"];
const after = ["apple", "pear"];
console.log(JSON.stringify(before) === JSON.stringify(after));
console.log(JSON.stringify([...before].toSorted()) === JSON.stringify([...after].toSorted()));

Expected output

false
true

MDN documentation →

map, filter, and holes

map() and filter() return new arrays. They do not deeply clone objects stored in the array. If you change a property on a selected object, the original array sees the same object.

map() skips empty slots in a sparse array. JSON.stringify later turns those holes into null, which is a different value from a missing slot.

Array.prototype.map and filter

array.filter(callback)
array.map(callback)

filter() keeps entries for which the callback returns a truthy value. map() builds a new array of callback results. Both leave the original array’s length and slots alone, but they reuse object references.

ParameterDescription
callbackA function that receives the current element, its index, and the array. A callback written as a block body must use return.

Returns: A new array.

  • The objects inside the new array are the same objects as in the original array unless you create new ones in the callback.
javascript
const projects = [{ name: "Notebook", done: false }];
const selected = projects.filter((project) => !project.done);
selected[0].name = "changed";
console.log(projects[0].name);

Expected output

changed

MDN documentation →

Sparse arrays and map

array.map(callback)

Empty slots are not visited by map(), but they still occupy a position. join() leaves those positions empty; JSON.stringify writes null.

javascript
const sparse = [1, , 3];
console.log(sparse.length);
console.log(sparse.map((n) => n * 2).join(","));
console.log(JSON.stringify(sparse.map((n) => n * 2)));

Expected output

3
2,,6
[2,null,6]

MDN documentation →