loading...
Cover image for Useful JS array methods to level up your game!

Useful JS array methods to level up your game!

thesanjeevsharma profile image Sanjeev Sharma Updated on ・4 min read

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]

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

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

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" }

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

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. ✌️

Posted on by:

thesanjeevsharma profile

Sanjeev Sharma

@thesanjeevsharma

I am a Full stack developer based in India!

Discussion

markdown guide
 

Great post! I would be wary about using reduce though it's often advised against usage especially from most eslint rulesets. Often due to the fact (as you even mentioned in the post) that reduce looks hard and can be hard to understand.

 

"X looks hard" is not a good reason not to use something. reduce (or fold, or inject, or whatever other programming languages call it) is an incredibly useful function and should be used.

 

Thank you.

And reduce() is actually very simple, once you get it. My life has been a lot easier with reduce().

 

I do agree that reduce isn't that complicated but I was trying to just explain (which I may have done badly) that instead of using reduce its often better to avoid it and using something simpler to understand. For example using .sum is a lot better than using reduce because it's self descriptive in what it does.

That doesn't mean there isn't a usecase for reduce I'd just use it sparingly. But of course that's just my opinion!

 

I find staticMap() a very underrated function

 

I am not sure what you're talking about. Can you provide a reference? I'd love to read about it.

 

Sorry, its flatMap

developer.mozilla.org/en-US/docs/W...

The array.map() returns a single item per item in the array. with flatMap you can return multiple or no items per item in the array you are iterating over

Yes! I've used it recently. But I think it's for specific cases only. Not something you'd use every day. But again, really useful and a pretty one. ✌️

Maybe, I'll make a Part 2 for these kinds of methods. 😉