Shinchan, Masaochan, Kazamachan walk into a pizza shop. The menu only has six options. They have a specific condition to be sufficed before making a purchase. Condition of Shinchan
- No Capsicum
Condition of Kazama
- Must include cheese.
Collective Condition
- The total should be below 1000.
Let's understand the array of methods with the processes they used to make a purchase.
Step 1
The shop provides taste before you buy. They demand to taste samples. The shopkeeper maps through all five pizzas and gives a slice of them.
const menu = ["pizza 1", "pizza 2", "pizza 3", "pizza 4", "pizza 5", "pizza 6"];
const tastesamples = menu.map(item => `A slice of ${item}`);
console.log(menu);
console.log(tastesamples);
/*
['pizza 1', 'pizza 2', 'pizza 3', 'pizza 4', 'pizza 5', 'pizza 6']
[
'A slice of pizza 1',
'A slice of pizza 2',
'A slice of pizza 3',
'A slice of pizza 4',
'A slice of pizza 5',
'A slice of pizza 6'
]
*/
Step 2
Now Shinchan and Kazama will filter out the options that don't meet their condition.
const menu = [
{
id: 1,
name: "pizza 1",
price: 258,
ingredients: ["cheese", "tomato", "jalapeno"],
},
{
id: 2,
name: "pizza 2",
price: 208,
ingredients: ["cheese", "tomato", "jalapeno"],
},
{
id: 3,
name: "pizza 3",
price: 298,
ingredients: ["capsicum", "cheese", "tomato", "mushroom"],
},
{
id: 4,
name: "pizza 4",
price: 529,
ingredients: ["tomato", "cheese"],
},
{
id: 5,
name: "pizza 5",
price: 568,
ingredients: ["baby corn", "egg", "basil"],
},
{
id: 6,
name: "pizza 6",
price: 568,
ingredients: ["baby corn", "egg", "basil", "mushroom", "tomato"],
},
];
Shinchan's condition
const shinsarray = menu.filter(item => !item.ingredients.includes("capsicum"));
console.log(shinsarray);
Kazama's condition
const kazarray = shinsarray.filter(item => item.ingredients.includes("cheese"));
console.log(kazarray);
Step 3 Now let's write a pure function to check if our order fits our budget.
function isbudgetfriendly(array) {
const total = array.reduce((acc, item) => acc + item.price, 0);
if (total < 1000) console.log(true);
else console.log(false);
}
console.log(isbudgetfriendly(kazarray)); // true
Since our order is budget-friendly we can go ahead with it.
Quick summary
- Map function maps through the array.
- While this mapping goes on, we can operate the elements mapped.
- The operation performed on the elements is passed as a callback function.
- The filter function takes a callback function as an argument.
- This function checks if each element sufficed specified condition.
- If the outcome is true, the element passes.
- The reduce function takes a callback with two parameters a) Accumulator b) Current item.
- We can operate the current item and also store the outcomes from the previous ones in the accumulator.
- It has predominant use in going from many to one.