JavaScripts comes with some amazing methods to play with the array. Let’s explore them…

1) map()

What you usually do when you have to iterate through every item in an array? Most probably you run for loop in that array. But there is a method built-in with JavaScript which is called map(). Here is an example of it.

let numbers = [18, 21, 32, 49, 5, 6, 7, 8];
const mapResult = numbers.map(number => number * 2);
console.log(mapResult)

// Expected output
// [36, 42, 64, 98,10, 12, 14, 16]

The map method takes an argument which is every element of an array. Then it does some operations with that element and returns a new array.

2) filter()

The filter method is used when you have to filter some elements from an array if they pass the test implemented by the provided function. It is helpful when you have a large array and want to filter some items of the same category. Let’s see how it works…

const names = ['Tom', 'Cruise', 'Ema', 'Watson'];
const result = names.filter(name => name.length < 6);
console.log(result)

// Expected output
// [ 'Tom', 'Ema' ]

In this case, the filter function is filtering the names which lengths are less than 6. That’s why we got Tom and Ema.

3) find()

Let’s say, you want to find a specific item from an array. Now you can go through the whole array and see if the item is there or not. But what if the array is populated with 1000 items? Here find method comes in the picture. Let’s see how it works…

let numbers = [18, 21, 32, 49, 5, 6, 7, 8];

const found = numbers.find(number => number < 10)
console.log(found);
//Expected Result: 5

In this case, this find method is iterating through all the items in the array and checking if the item is less than 10.

#array-methods #javascript-arrays #javascript #coding

10 Tips and Tricks to Work Fast with Array in JavaScript
30.70 GEEK