Day 20: Consolidation 3
Lesson 3: Higher Order Functions 2
1. findIndex
find
gives you the element from an array, findIndex
will give you the index (location) of the first found item in the array.
Using the same example as find()
:
This will log 1
since that's the index of the car with the model of "Juke" (remember that arrays start their index at 0, not 1).
Change the code above to look for a car model that isn't in the list, you'll see it now prints -1
. This is JavaScripts odd way of saying "Couldn't find an item"
2. some
some
let's us see if any items in our array return try for a condition. In a way this is like find
and findIndex
in that if they find something you will get an item or a number, and if they don't you will get undefined or -1 BUT instead some
will simply return true or false. It returns true when at least one array element returns true for your condition or false if none of them do.
Let's see if any of our cars have top speeds over 140 and then 250.
3. every
If some
tells us if any items match our condition it should be clear that every
tell us if every element matches our condition. It returns true if every element returns true and false as soon as one of them doesn't match our condition. Keeping with the car functions, heres an example.
4. reduce
Ahhh, reduce
every new developers nemesis. reduce
lets us apply a function to every element in an array, return a value and then pass that value into the next iteration of the function.
In plain English we could take a list of numbers 1, 2, 3, 4, 5
and sum them up with reduce starting with 0 like this.
- 0 + 1 = 1 ➡️ return 1
- 1 + 2 = 3 ➡️ return 3
- 3 + 3 = 6 ➡️ return 6
- 6 + 4 = 10 ➡️ return 10
- 10 + 5 = 15 ➡️ return 15
And so we get 15 as the result.
We can even use reduce
to transform an array of objects. Let's take a list of students and just make a comma separate list from an array of more complex objects.
5. reduceRight
Like reduce
but starts at the end and works backwards. It's like calling .reverse()
on you array first and then calling .reduce()