Useful JS array methods to level up your game!

Sanjeev Sharma - Aug 2 '20 - - Dev Community

Hi there!

Today, I'll be sharing some useful JS array methods that I use daily. These methods will surely level up your game as a beginner. 💪 Let's dive into those now.

1. map()

According to MDN:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Basically, map() is used for data transformation. Remember this!
Let's understand map() with an example.

// I want squares and cubes of all these numbers
const numbers = [1, 2, 3, 4, 5]

// using forEach()
const squares = []
numbers.forEach(number => squares.push(number**2))
// Output: [1, 4, 9, 16, 25]

// using map()
const cubes = numbers.map(number => number**3)
// Output: [1, 8, 27, 64, 125]
Enter fullscreen mode Exit fullscreen mode

In the example, you can see how easy it was to calculate cubes as compared to squares.
map() takes a function(here it's an arrow function) as its argument. That function will be executed for every element of numbers array and result of that function will be stored in the new array cubes.

You can also pass some optional arguments. The order for arguments is:

  1. currentValue - The value in the array for which function is being executed. In our case, its number.
  2. index - Index of the currentValue.
  3. array - Array on which map is being run. In our case, it's numbers.
  4. this - Value to be used as this when executing this function.

2. filter()

According to MDN:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Basically, you provide a function that is run against every element in the given array. If that function evaluates to true, that element is pushed to the new array else not.
Let's understand 'filter()' with an example:

// Club entry list
const persons = [
  {
    name : 'Mark',
    age : 19,
    gender: 'M'
  },
  {
    name : 'Jenny',
    age : 17,
    gender: 'F'
  },
  {
    name : 'Ben',
    age : 15,
    gender: 'M'
  },
  {
    name : 'Julia',
    age : 23,
    gender: 'O'
  },
]


const adultsOnlyList = persons.filter(person => person.age > 18)
// Mark and Julia

const noMenList = persons.filter(person => person.gender !== 'M' && person.age > 18)
// Julia
Enter fullscreen mode Exit fullscreen mode

In the above example, some people want to enter a club but we cannot allow anyone that is below 18. So, we generate a adultsOnlyList with the help of filter() function. Note that function inside filter() should always return a Boolean.
Club has a special day too when males are not allowed. So, we generate another list noMenList by extending our previous function. Ultimately, if your function returns a Boolean, it will work.

You can also pass some optional arguments. Those arguments are same as mentioned in map().

3. reduce()

According to MDN:

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

Basically, as the name suggests it will perform some operation on your array and reduce it to a single value. For example, operations like sum, average, factorial, etc. can be easily done by reduce().
Let's understand reduce() with an example:

// What's the total for these items?
const shoppingCart = [
  {
    name : 'Potato',
    price: 40,
  },
  {
    name : 'Tomato',
    price: 60
  },
  {
    name: 'Bread',
    price: 21
  }
]

const total = shoppingCart.reduce((sum, item) => sum + item.price, 0)
// 121
Enter fullscreen mode Exit fullscreen mode

People find reduce() hard at the first look. 😨 Don't be sacred. Let's break it down.
I've passed two arguments to the reduce() function. The first one is a function that we want to execute for each element.
(sum, item) => sum + item.price
That function has two arguments sum and item. sum will store our value after every iteration and item will always have the element we are currently iterating on.
What about the second argument? So, the second argument is nothing but sums' initial value. If you don't pass it, then shoppingCart's first element will be stored in sum and looping will start from the second element.

4. find() and findIndex()

Let's take these two methods together because they are very similar. 👀

find()

According to MDN:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

Basically, you pass a function to find() and whichever element evaluates to true will be returned. If none passes, you'll get undefined.
Let's understand this with an example:

// I want to buy something for $120
const accounts = [
  {
    name : 'Citi Bank',
    balance: 100
  },
  {
    name : 'Bank of America',
    balance: 150
  },
  {
    name: 'Capital One',
    balance: 170
  }
]


const account = accounts.find(account => account.balance > 120)
// { balance: 150, name: "Bank of America" }
Enter fullscreen mode Exit fullscreen mode

So, I have multiple accounts and I am looking for an account that has at least $120 balance. Though, there are two accounts that satisfy this condition but find() returns the first element that passes the test.

findIndex()

According to MDN:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

Basically, the same thing as find(). Only difference is: It returns the index instead of the element. Returns -1 instead of undefined, if no element passes the test.

Let's run the same example with findIndex():

const accountIndex = accounts.findIndex(account => account.balance > 120)
// Output: 1
Enter fullscreen mode Exit fullscreen mode

Nothing to explain, I guess. Pretty straightforward.

That's all folks! 👋

Part 2 of useful JS array methods. It has some uncommon ones. 😉

Hope you learned something. ✌️

. . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player