Very often the callback function tends to be simple and can be written as an arrow function to simplify things even further. It takes two arguments with the first one being a callback function and the second one the initial value. ![]() ![]() Instead of making use of the for loop, we’re using the reduce method. GetAverageAge(users) // Result is 32.66.ĭo you see what happened there? Let’s break it down. const users = Ĭonst sum = users.reduce((prev, curr, index, array) => prev + curr.age, 0) We will first do it in the simplest way possible, by utilising the for loops that iterate over the array. Given an array of objects, where each object has two properties, name and age, calculate the average age of all the users. Later we will improve on it by using the reduce JS method available on the arrays. ![]() So you have an array in the state of your application and need to process it somehow? Let’s take a look at how to write a simple algorithm to sum all the values of the array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |