bhylu.com

Advertisements

JS Array Sort

The default sort compares string representations. Give numeric data a comparison function.

Where to run this

This example uses the JavaScript console playground. Select Run to execute it; the example does not run on this lesson page.

A practical example

JavaScript

const prices = [12, 3, 20];
const sorted = [...prices].sort((a, b) => a - b);
console.log(sorted);

What happens

The new list is [3,12,20] and prices stays unchanged.