Keep the Messages Behind the Count

In Count Matching Messages, your loop reported 2 delivery messages. That’s a good start, but sooner or later someone will ask, “Which two?” A bare number can’t answer that. Your report should keep the messages behind the count, so you can point to each one, read its text, and say why it’s in.

By the end of this lesson, you’ll be able to build a new list of the messages that match a rule, keep their IDs, and read the count from that list.

Start an Empty List and Add to It

In Many Messages in One List, you met [] as the empty list on a quiet day. It’s also the right way to start a list you’re about to fill. To add a value to the end of a list, you call .push() on it with that value in the parentheses:

Language: JavaScript
> const selected = [];
undefined
> selected.push({ id: 7, topic: "delivery" });
1
> selected.push({ id: 9, topic: "delivery" });
2
> selected.length
2

Each push() changes the list that selected already names. The list starts with no entries, gets one, then two, and .length reads how many it holds right now.

The 1 and 2 are what push() hands back: the list’s new length, not the list. So call push() on its own line, and never write selected = selected.push(...), which would try to point selected at a number.

You may wonder how a list declared with const can grow. The name selected never gets pointed at a different list, so const is happy. The list it names is what gets longer.

Keep Each Matching Message

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.