8 Modern Array Methods that Every Developer Should Know

8 Modern Array Methods that Every Developer Should Know

Incredibly useful methods to make your life easier

Photo by [Volodymyr Hryshchenko](https://cdn.hashnode.com/res/hashnode/image/upload/v1630754141503/TvUNgwGtN.html) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)Photo by Volodymyr Hryshchenko on Unsplash

While performing array operations with long lines of code, have you ever stopped and wondered if there was an easier way to do it?

In JavaScript, there are various insanely useful array methods available to us. And when used correctly, they can help you achieve great things with just a few lines of readable code.

We will be looking at 8 array methods can drastically decrease your workload and benefit you.

Let’s get started.

1. Map

The Map method allows you to convert your existing array into a new array with your specified operation.

var numbers = [4, 9, 16, 25];

var x = numbers.map(v=> 2*v)

console.log(x)

console.log(numbers)

The map method will return a new array and store it in the variable ‘x’. The original array ‘numbers’ will remain the same.

The expected output of the code above will be:

[8,18,32,50] // x

[4,9,16,25]  // numbers

2.Find

This is another useful.

What the find method does is that it allows us to find a particular object in the array.

The syntax is similar to the map method except we have to return true or false based on some particular check.

This method stops iterating over the array as soon as true is returned for the first time.

It is worth noting that it returns the very first time in the array that matches our search query.

var data = [
  {item:'Coffee', price:10},
  {item:'Tea',price:12},
  {item:'Shirt',price:25},
  {item:'Pen',price:6},
  {item:'Shirt', price:10}
];
var searchEle=data.find(v => v.item=='Shirt')
console.log(searchEle)

Output:

{
  item:"Shirt",
  price:25
}

As you can see, we have two objects in our array ‘data’ with the value of ‘item’ as ‘Shirt’, however, the .find() method has only returned the first object matching our condition.

3. Filter

As the name suggests, this method allows us to filter our array.

Like the above 2 methods, this method doesn’t alter the original array as well.

We will be using the same ‘data’ array in the previous example and we will be filtering out elements whose price is under 10.

var data = [
  {item:'Coffee', price:10},
  {item:'Tea',price:12},
  {item:'Shirt',price:25},
  {item:'Pen',price:6},
  {item:'Shirt', price:10}
];
var filteredArr=data.filter(v => v.price>=10)
console.log(filteredArr)

If you take a look at the function inside the filtermethod, you can see that we are checking if the ‘price’ property of the current object has a value greater than equal to 10.

If it does, the element is added to our “filteredArr” array.

The output of the code snippet above:

[
  {
    "item": "Coffee",
    "price": 10
  },
  {
    "item": "Tea",
    "price": 12
  },
  {
    "item": "Shirt",
    "price": 25
  },
  {
    "item": "Shirt",
    "price": 10
  }
]

Another interesting thing you can do is that you can achieve the functionality of the find() method using this method. However, there would be one difference.

When using the findmethod, we only get the first element that matches our search query, and with the filtermethod, we will obtain all the elements that match our query.

This would be better showcased if we use the same example like the one we used to show the findmethod, only this time we will use the filtermethod to achieve the same purpose.

var data = [
  {item:'Coffee', price:10},
  {item:'Tea',price:12},
  {item:'Shirt',price:25},
  {item:'Pen',price:6},
  {item:'Shirt', price:10}
];

var searchEle=data.filter(v => v.item=='Shirt')

console.log(searchEle)

We just had to swap the ‘find’ keyword with ‘filter’ and the rest of the code remains the same. However, the output would look different.

[
  {
    "item": "Shirt",
    "price": 25
  },
  {
    "item": "Shirt",
    "price": 10
  }
]

As stated before, unlike the findmethod, the filter will return every objected for which the function returns true and not stop the first time.

4. forEach

This method is a replacement of the for-loop.

Instead of writing the entire loop statement, we can use this method to achieve the same.

However, this method doesn’t return an array and simply loops over them.

var numbers = [4, 9, 16, 25];

numbers.forEach(v=> console.log(v))

This is a good method when you want to simply loop over the elements in the array.

However, this does not stop you from performing other operations such as assigning values of the array to some other array based on some condition.

var numbers = [4, 9, 16, 25];
var s=[];
numbers.forEach(
  v=> v%2==0 ? //checking for even numbers
  s.push(v*v): //adding their square to another array
  null)
console.log(s)

But these operations are better to be performed by the filtermethod as stated earlier in the article.

I just wanted to show the possibility.

5. Every

This method checks that every single item in the array meets some particular criteria.

This method returns a boolean value instead of an array.

This can be useful when you have to make sure that every element has some particular property or some value.

var data = [

{name:'Science', results:'passed'},

{name:'Maths',results:'failed'},

{name:'Computer',results:'passed'},

];

var finalResult=data.every(v => v.results=='passed')

console.log(finalResult) // => false

For example, in our code snippet above, the student’s exam results are stored in the array ‘data’, and to pass the final exams, he has to pass in every one of the subjects.

Hence, we have used the every() method to check if he passed in all the subjects.

You can even check if a particular value exists or not as shown below:

var data = [

{name:'Science', results:'passed'},

{name:'Maths',}, //here results is missing

{name:'Computer',results:'passed'},

];

var everyEle=data.every(v => v.results)

console.log(everyEle) // => false

6. Some

What if we wanted to check if some of the elements meet our conditions and not every element?

This is where the somemethod comes.

Like the everymethod, this method too returns a boolean. However, it returns true whenever at least one of the elements meet the condition.

var data = [

{name:'Science', results:'passed'},

{name:'Maths',results:'failed'},

{name:'Computer',results:'passed'},

];

var finalResult=data.every(v => v.results=='passed')
console.log(finalResult) // => true

7. Includes

This is a very straightforward method that checks if a particular element is included in the array or not.

It is worth mentioning that the includes method is available for String as well and offers the same functionality.

var numbers = [4, 9, 16, 25];
var s=numbers.includes(4)
console.log(s) // => true

This method also returns a true or false.

Additionally, you can provide a search starting position as well as a second parameter.

var numbers = [4, 9, 16, 25];

var s=numbers.includes(4,2)//(element,starting index)

console.log(s) // => false

8. Reduce

This method is relatively complex when compared to the methods we have discussed so far.

We have calculated the total price of the elements present in the ‘data’ array using the reducemethod.

Notice how we didn’t declare a global variable to keep the total in but instead used the one provided by the method itself.

var data = [
  {item:'Coffee', price:10},
  {item:'Tea',price:12},
  {item:'Shirt',price:25},
  {item:'Pen',price:6},
  {item:'Shirt', price:10}
];
var totalPrice=data.reduce((total,current) => {
  return current.price+total
},0)
console.log(totalPrice)

For starters, this method takes 2 arguments instead of one.

The first argument is the returned value of the last iteration of the function, while the second argument is the actual current element in the array.

Therefore, the ‘total’ (first argument) contains the sum of ‘current.price’ (i.e price value of the current object) and total.

This value of ‘total’ is returned by the function and forms the first argument of the next iteration of the function.

Also, notice that we have passed another argument after the function. That is the default value. We want the ‘total’ to start at 0 and hence passed 0 as a second parameter after the function.

Final Thoughts

JavaScript is the dominant client-side scripting language and even though it is a very beginner-friendly language, it is widely used in different spheres.

JavaScript applications are becoming increasingly complex and the language adds features and updates itself to meet the demand.

It is imperative to learn the best and modern practices to reduce the workload and build vital apps with readable and simple code.

JavaScript provides various array methods that aim to simplify the operations related to array drastically. However, it is important to understand when to use and for what purposes.

Using the best features offered by JavaScript and understanding when to use them can also provide an edge over others in technical interviews.

Enjoyed this article? If so, get more similar content by **subscribing to Decoded, our YouTube channel!**

Did you find this article valuable?

Support Smart Dev Blogs by becoming a sponsor. Any amount is appreciated!