Home › Learn › JavaScript › Arrays

Sorting and slicing

Lesson 20 of 40. Order arrays correctly and take parts of them.

items.sort() sorts in place and, by default, compares as strings, so [10, 9, 1].sort() gives [1, 10, 9]. For numbers pass a comparator: nums.sort((a, b) => a - b) ascending, b - a descending. For objects compare a field: people.sort((a, b) => a.age - b.age). toSorted returns a sorted copy instead of changing the original; so does [...items].sort(...).

slice(start, end) copies part of an array (end excluded; negatives count from the end), join(", ") makes a string, reverse() flips in place, and the spread [...a, ...b] concatenates.

const scores = [70, 95, 88];
const top = [...scores].sort((a, b) => b - a).slice(0, 2);
console.log(top);              // [95, 88]
console.log(scores);           // unchanged
console.log(top.join(" & "));  // 95 & 88

Your task

Write byLength(words) returning a new array sorted by length, alphabetically among equal lengths (localeCompare compares strings), without changing the input, and topScores(scores, n) returning the n largest scores from highest to lowest, also without changing the input.

Hint 1

[...words].sort((a, b) => a.length - b.length || a.localeCompare(b))

Hint 2

[...scores].sort((a, b) => b - a).slice(0, n)

Show the solution
function byLength(words) {
  return [...words].sort((a, b) => a.length - b.length || a.localeCompare(b));
}

function topScores(scores, n) {
  return [...scores].sort((a, b) => b - a).slice(0, n);
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.