Tools for working with arrays

INPUT · Slides

Collecting everything that matches

01 / 05

You want all of them

find gave you the first one. But when you want to know all who passed, or list every product in stock, one is not enough.

You could write it with for and push, but the method made for it is shorter.

02 / 05

filter sends back a new array

What you hand filter is the same condition function as find. What differs is what comes back.

  • findthe first one matching
  • filtera new array of every item matching

Picture sieving them with the condition.

const nums = [4, 9, 12, 7];const isBig = (n) => {  return n >= 8;};console.log(nums.filter(isBig));

Result

[9, 12]

03 / 05

The original array does not change

filter only makes a new array and sends it back. The original is left as it was.

What comes back is an array, so you can count it with .length or take items out by number.

const scores = [45, 82, 60];const isPass = (s) => {  return s >= 60;};const passed = scores.filter(isPass);console.log(passed);console.log(passed.length);console.log(scores);

Result

[82, 60]
2
[45, 82, 60]

04 / 05

None means an empty array

When not a single item matches, what comes back is not undefined but an empty array [].

That is the difference from find. filter sends back "the collected result", so when nothing collects you get an array with nothing in it.

const nums = [1, 2, 3];const isBig = (n) => {  return n >= 8;};const big = nums.filter(isBig);console.log(big);console.log(big.length);

Result

[]
0

05 / 05

Narrowing an array of objects

A common use of filter is taking just the matching part out of an array of objects.

Having collected them, you can show them one at a time with forEach, or give the count with .length.

Right — let us narrow things down.

const items = [  { name: "pen", count: 3 },  { name: "notebook", count: 0 },];const inStock = (item) => {  return item.count > 0;};console.log(items.filter(inStock));

Result

[{ name: "pen", count: 3 }]