Getting the largest number from an array
To find the largest value in an array of numbers, we can spread that array into Math.max() instead of manually iterating over it.
Read fire tipWant to know how many elements in an array match a condition? We can use this to count all elements in an array that return true
for a function that checks this condition.
// takes an array and a function to check each element in the array against
const countBy = (array, checkFunction) => {
return array.reduce((count, element) => {
return checkFunction(element) ? count + 1 : count
}, 0)
}
// we can count how many numbers in an array are smaller than a given limit
countBy([-4, 3, -7, 5, 0, -3, 1, -8], number => number < 0)
// ⇒ 4
// we can count how many strings are exactly four characters long
countBy(['John', 'Paul', 'George', 'Ringo'], name => name.length === 4)
// ⇒ 2
// we can also check if objects have a certain value in a property
countBy([
{
name: 'Bulbasaur',
types: ['Grass', 'Poison']
}, {
name: 'Nidoqueen',
types: ['Poison', 'Ground']
}, {
name: 'Abra',
types: ['Psychic']
}, {
name: 'Tentacool',
types: ['Water', 'Poison']
}
], pokemon => pokemon.types.includes('Poison'))
// ⇒ 3
To find the largest value in an array of numbers, we can spread that array into Math.max() instead of manually iterating over it.
Read fire tipWe cannot use the typeof operator in JavaScript to check if something is an array or not. Luckily, there is a helper function on the Array prototype for that.
Read fire tipWhen the if-branch already returns, we can omit the keyword else. The execution will only go beyond the if-branch if it doesn’t apply anyways.
Read fire tip