Count and Select Matching Items

In the last lesson, two loops had a starting value before their first pass. The running total began at 0, and the list of numbered songs began as an empty array. Both grew by one step per item and held the answer once the loop ended.

That works when every item counts. Real questions are often pickier, such as how many items on a packing list are snacks or which items aren’t food. To answer them, the loop has to look at each item and decide whether it belongs in the answer.

In this lesson, you’ll write two small functions that make that decision. One counts the items that match a rule, and the other selects them into a new list. At the end, you’ll turn both into a short report about a list of your own.

Recall How to Write a Condition

Both patterns rest on a skill from an earlier course: writing a condition that’s either true or false. Here’s a warm-up. With const item = "snacks";, predict the result of each condition:

  • item === "snacks"
  • item === "Snacks"
  • item !== "tent"
  • item.length <= 4

Then type node in the terminal to open the REPL and check your answers.

Language: JavaScript
> const item = "snacks";
undefined
> item === "snacks"
true
> item === "Snacks"
false
> item !== "tent"
true
> item.length <= 4
false

The second one is false because === compares strings character by character, and a capital S is a different character from s.

The !== operator means “is not equal to,” so it’s true for any string other than "tent". The last one checks the string’s length, which is 6.

Keep these in mind. In a moment, one of them goes inside a loop, which checks it once for every item. Type .exit to leave the REPL.

Count Only the Items That Match

Picture a camping weekend with friends. Everyone added what they’re bringing to one shared list, and you suspect there’s a lot of food on it. Create camping.js in your course folder.

Language: JavaScript Filename: camping.js
const shared = [
  "tent", "snacks", "lantern",
  "snacks", "map", "lantern", "snacks"
];
console.log(shared.length);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.