Map in js arrays is used in place of loops whenever we need to use loops we use map method. map method is used to map every element of array. Map transform each element in an array and returns a new array with the transformated values.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map
(function(num) {
return num * 2;
});
console.log(doubled);
// [2, 4, 6, 8, 10]
Filter is also the advanced method of js arrays which is used to filter out the values of an array. It returns something when the condition meet otherwise the filter method is not work.
const names = ["Ali", "Sara",
"Ahmed", "John", "Ayesha"];
const aNames = names.filter
(function(name) {
return name.startsWith("A");
});
console.log(aNames);
// ["Ali", "Ahmed", "Ayesha"]
forEach method is also like map method which is work on every index of the array, it can change, update, delete or modify the array but nothing gives as a return.
const names = ["Ali", "Sara", "John"];
names.forEach(function(name) {
console.log(name);
});
const numbers = [10, 20, 30];
numbers.forEach((num, index) => {
console.log(`Index ${index}: ${num}`);
});
reduce() is used to reduce an array to a single value by running a function on each item, one by one, like calculating sum or product merging data and building up somethign like string or objects.
const names = ["Ali", "Sara",
"Ahmed", "John", "Ayesha"];
const aNames = names.filter
(function(name) {
return name.startsWith("A");
});
console.log(aNames);
// ["Ali", "Ahmed", "Ayesha"]