Useful array methods

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Useful array methods

JavaScript contains useful methods that can help you manipulate arrays. You’ll learn four of them in this lesson. They are:

  1. findIndex
  2. find
  3. filter
  4. map

findIndex

findIndex lets you find the index of an item in an array. It loops through every item in the array and returns the first truthy expression.

The syntax looks like this:

const index = array.findIndex((currentItem, index) => {
  // return a truthy expression here
})

Its much easier to explain Array.findIndex with an example, so let’s do that. Let’s say you have an array of objects. Each object is a person, and each person has a name.

const people = [
  {name: 'Zell'},
  {name: 'Vincy'},
  {name: 'Casper'}
]

You want to know the position of the person named Casper in the people array. To do so, you can use Array.findIndex and check if the name property in each object matches Casper.

const casperIndex = people.findIndex(person => person.name === 'Casper')
console.log(casperIndex) // 2

find

find works the same way as findIndex, but find returns the item instead of the index.

const casper = people.find(person => person.name === 'Casper')
console.log(casper) // {name: 'Casper'}

filter

array.filter returns a new array that contains a subset of the original array. Items will be added to the new array if you return a truthy expression.

const filteredItems = array.filter((currentItem, index) => {
  // return a truthy expression to include in filteredItems
})

Once again, its easier to explain filter with an example, so let’s do that.

Let’s say you have a list of numbers. You want to make another list of numbers that are bigger than ten. You can do this easily with filter.

const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]
const biggerThan10 = numbers.filter(num => {
  if (num > 10) return true
})

console.log(biggerThan10) // [12, 18, 11, 50]

To shorten the code slightly, you can return the if condition because a truthy expression evaluates to true.

const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]
const biggerThan10 = numbers.filter(num => num > 10)

map

map returns a new array that contains the same number of items in the original array. Each item in the new array item is the value you return in the callback.

const newArray = Array.map((currentItem, index) => {
  // return the transformed value
})

Once again, its easier to explain Array.map with an example, so let’s do that.

Let’s say you have a list of numbers. You want to create a new array that contains another list of numbers, but each item is multiplied by five.

const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]
const multipliedBy5 = numbers.map(num => {
  return num * 5
})

console.log(multipliedBy5) // [5, 60, 20, 90, 45, 35, 55, 15, 250, 25, 30]

Since there’s only one line of code, you can use an implicit return:

const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]
const multipliedBy5 = numbers.map(num => num * 5)

map is super versatile. It can be used to simplify arrays or even modify other types of values.

Modifying an array value

Let’s say you have an array of todos. You want to add the string I need to in front of each todo item.

const todos = ['buy eggs', 'feed my cat', 'water plants']

// What you want:
// [
//   'I need to buy eggs',
//   'I need to feed my cat',
//   'I need to water plants',
// ]
const todoStrings = todos.map(todo => `I need to ${todo}`)

console.log(todoStrings)
// [
//   'I need to buy eggs',
//   'I need to feed my cat',
//   'I need to water plants',
// ]

Simplifying arrays with map

Let’s say you have an array of objects. Each object contains a person’s first and last name.

const people = [{
  firstName: 'Zell',
  lastName: 'Liew'
}, {
  firstName: 'Vincy',
  lastName: 'Zhang'
}]

From this list of people, you need to get an array of firstNames. To get this array, you can use map to loop through the array and return person.firstName.

const firstNames = people.map(person => person.firstName)
console.log(firstNames) // ['Zell', 'Vincy']

map vs forEach

Many people get confused between map and forEach. Here’s a quick way to remember what does what:

  1. Use map when you want to return a new array
  2. Use forEach when you want to do stuff

Chaining array methods

Since map and filter return arrays, you can perform another map or filter method immediately if you wish to.

For example, let’s say you want have a list of numbers. You want to multiply each number by five. After the multiplication, you want to get a list of numbers that are between 30 and 40.

Here’s how you might do it now.

const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]
const multipliedBy5 = numbers.map(num => num * 5)
const between30And40 = multipliedBy5.filter(num => num >= 30 && num <= 40)

If you chain array methods, you can do this:

const result = numbers.map(num => num * 5)
  .filter(num => num >= 30 && num <= 40)

Exercise

Complete these exercises with the following data:

  1. Find the index of Thomas Edison.
  2. Find the object that contains Winston Churchill.
  3. Create an array that contains people that died before 1940.
  4. Create an array that contains people that were alive between 1850 and 1970.
  5. Create an array that contains the firstName, lastName and yearsLived for each person (where yearsLived is the number of years the person lived).
  6. Get the total number of yearsLived of the people who were alive between 1750 and 1900.
const people = [
  { firstName: 'Benjamin', lastName: 'Franklin', yearBorn: 1706, yearOfDeath: 1790 },
  { firstName: 'Thomas', lastName: 'Edison', yearBorn: 1847, yearOfDeath: 1931 },
  { firstName: 'Franklin', lastName: 'Roosevelt', yearBorn: 1882, yearOfDeath: 1945 },
  { firstName: 'Napoleon', lastName: 'Bonaparte', yearBorn: 1769, yearOfDeath: 1821 },
  { firstName: 'Abraham', lastName: 'Lincoln', yearBorn: 1809, yearOfDeath: 1865 },
  { firstName: 'Mahatma', lastName: 'Gandhi', yearBorn: 1869, yearOfDeath: 1948 },
  { firstName: 'Winston', lastName: 'Churchill', yearBorn: 1874, yearOfDeath: 1965 },
  { firstName: 'Charles', lastName: 'Darwin', yearBorn: 1809, yearOfDeath: 1882 },
  { firstName: 'Albert', lastName: 'Einstein', yearBorn: 1879, yearOfDeath: 1955 },
  { firstName: 'Pablo', lastName: 'Picasso', yearBorn: 1881, yearOfDeath: 1973 },
  { firstName: 'Ludwig', lastName: 'Beethoven', yearBorn: 1770, yearOfDeath: 1827 },
  { firstName: 'Walt', lastName: 'Disney', yearBorn: 1901, yearOfDeath: 1966 },
  { firstName: 'Henry', lastName: 'Ford', yearBorn: 1863, yearOfDeath: 1947 },
  { firstName: 'Steve', lastName: 'Jobs', yearBorn: 1955, yearOfDeath: 2012 }
]

Answers

  • Find the index of Thomas Edison.
const index = people.findIndex(person => {
  const { firstName, lastName } = person
  return firstName === 'Thomas' && lastName === 'Edison'
})
  • Find the object that contains Winston Churchill.
const churchill = people.find(person => {
  const { firstName, lastName } = person
  return firstName === 'Winston' && lastName === 'Churchill'
})
  • Create an array that contains people that died before 1940.
const diedBefore1940 = people.filter(person => person.yearOfDeath < 1940)
  • Create an array that contains people that are alive between 1850 and 1970.
const aliveBetween1850And1970 = people.filter(person => {
  const { yearBorn, yearOfDeath } = person
  return yearBorn < 1970 && yearOfDeath > 1850
})
  • Create an array that contains the firstName, lastName and yearsLived for each person (where yearsLived is the number of years the person lived).
const peeps = people.map(person => {
  const yearsLived = person.yearOfDeath - person.yearBorn
  return {
    firstName: person.firstName,
    lastName: person.lastName,
    yearsLived
  }
})
  • Get the total number of yearsLived of the people who were alive between 1750 and 1900.
const aliveBetween1750And1900 = people.filter(person => {
  const { yearBorn, yearOfDeath } = person
  return yearBorn < 1900 && yearOfDeath > 1750
})

let totalYearsLived = 0
aliveBetween1750And1900.forEach(person => {
  const { yearBorn, yearOfDeath } = person
  const yearsLived = yearOfDeath - yearBorn
  totalYearsLived = totalYearsLived + yearsLived
})

console.log(totalYearsLived) // 891