Typorithm · medium

slice, splice, sort

array-mutatecollectionsslicesplicesort
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn slice, splice, sort

0%

Array Methods

slice returns a copy of a range and never mutates; splice mutates the array in place to remove or insert elements and returns what it removed; sort mutates in place and needs a numeric comparator because its default ordering is lexicographic (string-based).

slice(start, end) returns a shallow copy of the [start, end) range and leaves the original array untouched — it is the safe, non-mutating way to take a sub-array.

splice(start, count) mutates the array in place: it removes count elements starting at start (and can insert new ones), returning an array of the removed elements.

sort also mutates in place. Its default comparison is lexicographic — it converts elements to strings — so [30, 10, 20, 40] would sort to [10, 20, 30, 40] only if you pass a numeric comparator like (a, b) => a - b.

01

slice copies a range and does not mutate.

02

splice mutates in place and returns removed elements.

03

sort mutates and defaults to lexicographic order — pass a comparator.

const arr = [30, 10, 20, 40];
const head = arr.slice(1, 3);
const removed = arr.splice(1, 2);
arr.sort((a, b) => a - b);

Read the implementation

Connect each part of the code to the concept before you type.

1. slice copies

slice returns a shallow copy of the [1, 3) range and leaves arr unchanged.

const head = arr.slice(1, 3);

2. splice mutates

splice mutates arr in place, removing 2 elements from index 1 and returning the removed ones.

const removed = arr.splice(1, 2);

3. sort mutates

sort reorders arr in place; the (a, b) => a - b comparator sorts numerically.

arr.sort((a, b) => a - b);

4. Numeric comparator

Without a comparator, sort compares elements as strings, so a numeric comparator is required for numbers.

(a, b) => a - b

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

slice, splice, sort: Lesson & Practice · Typorithm | ApplyDjinn