Looping over arrays
Overview
Most array work means visiting each item: printing it, adding it up, checking it, changing it. You have three everyday tools:
- a
for…ofloop, when you want to do something with each item; forEach, the same idea written as a method call;- question methods —
find,some,everyand friends — when you’re looking for something.
The next topic adds map, filter and reduce, for building new arrays and values.
for…of
const scores = [8, 6, 9];
for (const score of scores) {
console.log(score);
}It’s short, readable, and you can use break, continue and even await inside it. When in doubt, start here.
Need the index too? Use entries():
for (const [i, score] of scores.entries()) {
console.log(`#${i + 1}: ${score}`);
}The classic for loop
The counting loop from Loops still has its uses — for example when you need to step by two, go backwards, or compare neighbouring items:
for (let i = scores.length - 1; i >= 0; i--) {
console.log(scores[i]); // backwards
}
for (let i = 1; i < scores.length; i++) {
const change = scores[i] - scores[i - 1]; // compare with the previous item
console.log(change);
}forEach
forEach calls a function for every item, passing the item, its index and the whole array:
scores.forEach((score, i) => console.log(i, score));It suits short, one-line actions and fits naturally at the end of a chain of array methods:
users.filter((u) => u.active).forEach((u) => sendReminder(u));You can’t
breakout offorEach. If you might stop early, usefor…ofor one of the methods below.
Two more forEach gotchas:
- It always returns
undefined. If you want a new array, usemapinstead. - It doesn’t wait for
asynccallbacks.items.forEach(async (i) => await save(i))starts all the saves at once and moves on immediately. Usefor…ofwithawaitto do them one at a time.
Asking questions
const lessons = [
{ title: 'Loops', minutes: 6 },
{ title: 'Closures', minutes: 9 },
];
lessons.find((l) => l.minutes > 8); // { title: 'Closures', … }
lessons.findIndex((l) => l.title === 'Loops'); // 0
lessons.some((l) => l.minutes > 8); // true — at least one
lessons.every((l) => l.minutes < 10); // true — all of themThese stop as soon as they know the answer, which makes them faster than looping through everything yourself.
| Method | Returns | When nothing matches |
|---|---|---|
find(fn) |
the first matching item | undefined |
findLast(fn) |
the last matching item | undefined |
findIndex(fn) |
the index of the first match | -1 |
findLastIndex(fn) |
the index of the last match | -1 |
some(fn) |
true if at least one matches |
false |
every(fn) |
true if all match |
true (for an empty array) |
includes(value) |
true if the value is present (===) |
false |
Note that every on an empty array is true — “all zero items pass” is technically true. Check length too if that matters.
find returns the real item
find gives you the actual object from the array, not a copy. Changing it changes the array’s item:
const lesson = lessons.find((l) => l.title === 'Loops');
lesson.minutes = 7;
lessons[0].minutes; // 7Don’t change the array while looping
Adding or removing items while you’re looping over the same array leads to skipped or repeated items:
const nums = [1, 2, 2, 3];
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 2) nums.splice(i, 1); // removes one 2, then skips the next!
}
console.log(nums); // [1, 2, 3]Instead, build a new array with filter:
const withoutTwos = nums.filter((n) => n !== 2); // [1, 3]Which one should I use?
| You want to… | Use |
|---|---|
| Do something with every item | for…of (or forEach for one-liners) |
Stop early, or await inside |
for…of |
| Get the first item that matches | find |
| Know where it is | findIndex |
| Check whether any / all match | some / every |
| Build a new array or total | map, filter, reduce (next topic) |
First unfinished topic
Return the title of the first topic whose done is false, or null if all are done. Then write allDone(list) that returns true only if every topic is done.
const topics = [
{ title: 'Loops', done: true },
{ title: 'Arrays', done: false },
{ title: 'Objects', done: false },
];
function nextTopic(list) {
// your code here
}
function allDone(list) {
// your code here
}function nextTopic(list) {
return list.find((t) => !t.done)?.title ?? null;
}
function allDone(list) {
return list.every((t) => t.done);
}Summary
for…ofis the simplest loop and supportsbreakandcontinue.forEachruns a callback for each item but can’t be stopped early.find/findLastreturn an item;findIndexreturns its position or -1.someasks “at least one?”;everyasks “all of them?” — both stop early.- Don’t add or remove items in an array while looping over it.