map filter reduce javascript
Map, Filter, Reduce javascript
//=================================
let myarray = [
{
name: "John",
city: "london",
dept: "computer",
salary: 1000,
},
{
name: "bella",
city: "new york",
dept: "fianance",
salary: 1000,
},
{
name: "justine",
city: "paris",
dept: "computer",
salary: 1000,
},
];
console.log("myarray : ", myarray);
// ----------------------------------
// map
let mapArray = myarray.map(function (item) {
return item.name;
});
console.log("mapArray : ", mapArray);
// ----------------------------------
//filter
let filterArray = myarray.filter(function (item) {
if (item.dept == "computer") {
return true;
} else {
return false;
}
});
console.log("filterArray : ", filterArray);
// ----------------------------------
//reduce
// 1.
let reduceArray1 = myarray.reduce(function (acc, item) {
return acc + item.salary;
}, 0);
console.log("reduceArray1 : ", reduceArray1);
// ------
// 2.
let reduceArray2 = myarray.reduce(
function (acc, item) {
if (item.dept == "computer") {
acc.com.push(item.name);
} else {
acc.finance.push(item.name);
}
return acc;
},
{ com: [], finance: [] }
);
console.log("reduceArray2 : ", reduceArray2);
// ----------------------------------