Other Handy Array Tricks

Grade 10, page 10 of 12. A one-minute read.

A few more tools worth knowing:

JavaScript
// includes: is it in there?
console.log([1, 2, 3].includes(2));

// flat: flatten nested arrays
console.log([[1, 2], [3, 4], [5]].flat());

// Array.from: make an array from something else
console.log(Array.from("hey"));
console.log(Array.from({ length: 5 }, (_, i) => i * 10));

// join, after a map
console.log(["a", "b", "c"].map((x) => x.toUpperCase()).join("-"));

It prints

true
[ 1, 2, 3, 4, 5 ]
[ 'h', 'e', 'y' ]
[ 0, 10, 20, 30, 40 ]
A-B-C

Array.from({ length: 5 }, (_, i) => i * 10) is a neat trick for creating a numbered list. The underscore _ is a common name for a parameter you don't need (here, the item, which doesn't exist yet). We only care about the index i.

Which method do I need?

Your questionMethodReturns
"Do something with each item"forEachnothing (undefined)
"Change every item"mapnew array, same length
"Keep only some items"filternew array, maybe shorter
"Find the first item that matches"findthe item, or undefined
"Where is the first match?"findIndexan index, or -1
"Does any item match?"sometrue / false
"Does every item match?"everytrue / false
"Combine everything into one value"reduceanything
"Put them in order"sortthe same (sorted) array

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning