JS Arrays
An array is an ordered, zero-indexed list. Arrays are objects under the hood but come with a rich set of methods for transformation, search, and iteration.
Creating and accessing
JS
const fruits = ["apple", "banana", "cherry"]; fruits[0] // "apple" fruits.length // 3 fruits[fruits.length - 1] // "cherry" (last item) fruits.at(-1) // "cherry" — modern equivalent
The methods you'll use weekly
| Method | Mutates? | What it does |
|---|---|---|
push / pop | Yes | Add / remove from the end. |
unshift / shift | Yes | Add / remove from the beginning. |
splice(i, n, …) | Yes | Remove and/or insert in the middle. |
slice(i, j) | No | Return a copy of a sub-range. |
map(fn) | No | Build a new array by transforming each item. |
filter(fn) | No | New array of items that pass a test. |
reduce(fn, init) | No | Boil items down to a single value. |
find / findIndex | No | First matching item / index. |
some / every | No | Any / all items pass a test (returns boolean). |
includes(x) | No | Is x in the array? |
sort(cmp) | Yes | Sort in place. Pass a comparator for numeric sort. |
join(sep) | No | Combine items into a string. |
Common pipelines
JS
const cart = [
{ name: "Apples", price: 2, qty: 3 },
{ name: "Bananas", price: 1, qty: 6 },
{ name: "Cookies", price: 4, qty: 1 },
];
// Total cost
const total = cart.reduce((t, item) => t + item.price * item.qty, 0); // 16
// Names of items costing > $1 each
const expensive = cart.filter(i => i.price > 1).map(i => i.name);
// Sort cheapest first (numeric, ascending)
const sorted = [...cart].sort((a, b) => a.price - b.price);
Tip: Default to non-mutating methods (
map, filter, slice, spread). They make state changes obvious and play nicely with most modern frameworks.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Arrays!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Build a new array with each number doubled.
const doubled = nums.
(n => n * 2);
Three letters — transforms each item.
Discussion
Loading…