Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the .map (), .reduce () and .filter () methods in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 06:15:48 10月04日 Update

This article mainly shows you "how to use .map (), .reduce () and .filter () methods in JavaScript". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn how to use .map (), .reduce () and .filter () methods in JavaScript.

Give examples of the three most commonly used methods: map, reduce, and filter.

Before COVID-19 's epidemic, we went to Paris for a holiday. So they went to the supermarket to buy some things. They bought food and groceries. But all the items are in euros, and they want to know the price of each item and the total cost of their food in RMB.

Since 1 euro is equal to 7.18 yen.

In the traditional way, we will use a classic loop to do this:

Const items = [{name: 'pineapple', price: 2, type:' food'}, {name: 'beef', price: 20, type:' food'}, {name: 'advocate', price: 1, type:' food'}, {name: 'shampoo', price: 5, type:' other'}] let sum = 0const itemsInYuan = [] for (let I = 0; I

< items.length; i++) { const item = items[i] item.price *= 7.18 itemsInYuan.push(item) if (item.type === 'food') { sum += item.price }}console.log(itemsInYuan)/*[ { name: 'pineapple', price: 14.36, type: 'food' }, { name: 'beef', price: 143.6, type: 'food' }, { name: 'advocate', price: 7.18, type: 'food' }, { name: 'shampoo', price: 35.9, type: 'other' }]*/console.log(sum) // 165.14现在我们来使用现在 JavaScript 提供的函数式编程方法来实现这个计算。const itemsInYuan = items.map(item =>

{const itemInYuan = {... item} itemInYuan.price * = 7.18return itemInYuan}) const sum = itemsInYuan.filter (item = > item.type = 'food'). Reduce ((total, item) = > total + item.price, 0)

The above example uses the map method to convert euros to yen, uses filter to filter out non-food items, and uses reduce to calculate the price sum.

That's all of the article "how to use the .map (), .reduce () and .filter () methods in JavaScript. Thank you for reading!" I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Method content euro article price Japanese yen goods food study help three things people RMB tradition common use sum cost way daily use Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Information Huawei MySQL Xiaomi