JavaScript Array Methods (forEach, map, some, find, filter & more)
in this article will see about JavaScript methods:
1- forEach(): This loop is going to run same times as the element we have in the array
example- lets say that you have an array of 4 different elements , forEach is going to run 4 different times.
its a good method to display each array or iterate to across different elements in for loop.
lets have variable : const cars = [
{
make: ‘BMW’,
carmodel: ‘Serie 3’,
year: 2012,
price: 30000
},
{
make: ‘Audi’,
carmodel: ‘A4’,
year: 2018,
price: 40000
},
{
make: ‘Ford’,
carmodel: ‘Mustang’,
year: 2015,
price: 20000
},
{
make: ‘Audi’,
carmodel: ‘A6’,
year: 2010,
price: 35000
}];
it is going t be like this
cars.forEach() than inside we can another function it is callback , will pass car there, use console.log(car);
it will be like this:
cars.forEach((car) => cosole.log(car)) ;
(this is arrow function in short)
2- map(): the syntax for map and forEach are same , only difference is that map is going to create to new array
lets create a new variable result and do map() array to it
let result = cars.map(car => {
return car;
});
console.log(result);
3- filter(): It filters the array by the values given by user.
lets create variable result and do filter() method to it.
let result = cars.filter(car => {
return car.price > 30000;
});
console.log(result);
this will return all cars greater than 30000
4- find(): This will return the first element that match the condition.
from filter() method example lets do find() method to it.
let result = cars.find(car => {
return car.price > 30000;
});
console.log(result);
so car with price 40000 will return first.
5- reduce(): This is going to execute output the result in a single value.
lets find out how much money will get after selling all cars.
reduce() will take 2 different arguments into functions first one is accumulator variable which hold values, which will increase lets call it total, second one is current object which is car,
let result = cars.reduce((total, car) => total + car.price, 0 );
console.log(result);
0 is because number start from 0.
so total of all cars is 125000.
6- some(): This function is going to return true or false if a condition is met.
if you have a list of products and want to check if product exists we can use some and this will retrieve true or false only.
example-
let result = cars.some(car => car.make === ‘BMW’);
console.log(result);
result is true as BMW exist.
let result = cars.some(car => car.make === ‘FERRARI’);
console.log(result);
result is false as FERRARI doesn’t exist.
thank you for reading, will be waiting for feedback.
stay tuned.