Tools for working with arrays

INPUT · Slides

Finding the one that matches

01 / 05

You only want the first one

"I want to find one person scoring 80 or more." "I want to find one product that has run out." What you want in cases like these is just the first one found.

forEach always works through every item, so it does not suit this. Use the method made for it.

02 / 05

find takes a condition

What you handed forEach was a function of "what to do". What you hand find is a function of the condition.

Write the function so it returns true or false. find tries it from the front in order and gives you back the first item that came out true.

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

Result

9

03 / 05

What comes back is the item itself

What find sends back is not true / false but the matching item itself.

So you can catch it in a variable and use it straight away, in a sum or on the screen.

const prices = [80, 150, 300];const isHigh = (p) => {  return p >= 100;};const found = prices.find(isHigh);console.log(found);console.log(found * 2);

Result

150
300

04 / 05

Not found means undefined

When not a single item matches, undefined comes back.

Catch it and check with if and you can write the "when it was not found" part too.

const nums = [1, 2, 3];const isBig = (n) => {  return n >= 8;};const found = nums.find(isBig);console.log(found);if (found === undefined) {  console.log("not found");}

Result

undefined
not found

05 / 05

Searching an array of objects

Where find really comes alive is hunting one entry out of an array of objects. Inside the condition, use . to look at a property.

What comes back is the whole object. So after finding it, you can use both the name and the age.

Right — let us go hunting.

const members = [  { name: "Yui", age: 12 },  { name: "Kai", age: 15 },];const isTeen = (m) => {  return m.age >= 13;};console.log(members.find(isTeen));

Result

{ name: "Kai", age: 15 }