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.
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.
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.
By the word Array methods, I mean the inbuilt array functions, which might be helpful for us in so many ways. So why not just explore and make use of them, to boost our productivity. Let’s see them together one by one with some amazing examples.