Array Methods! Pt. 4 (reduce, includes)

David Lago
3 min readOct 17, 2021

--

The final part of my array methods that I believe everyone should have a refresher on! Or at least try with their code sometime because there are some of these methods I myself haven’t used yet! With that being said, I’m gonna begin this blog with the reduce method.

The reduce method is a bit different. The reduce method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. This was defined by MDN Web Docs. From what I gathered from it is that the array must go through some type of preceding element such as addition or subtraction.

reduce method

Whats done with the code above is that we once again have our sneakers array hold values of sneakers with the key of name and price. We then create a const named total and have it set to sneakers using the reduce method, within the argument we then have currentTotal and sneaker. We use sneaker as an argument to go one level deeper and grab the price of the sneaker and have our current total increase by price, we then have it set to 0 at the end so when we add everything up we then console.log to print out the total of how much every sneaker would be together for a sum of 780. Its useful I think because theres going to be instances where you might have to grab some type of data from an array and get the total from it, such as the example above if someone were to purchase all the shoes.

Now for the final array method I’ll be mentioning is the includes method. The includes method determines whether an array includes a certain value among its entries, returning true or false as appropriate. Defined by MDN Web Docs, my interpretation for it is that if there were an array and we would need to find something thats within it and return a boolean which is the result of true or false.

includes method

Whats done within the example above is that we now have numbers within our array to make it more simple. We create two const’s which were named after two numbers we are seeking in the array, one of them being an integer of seven and the other being eight. Now what includes is doing within the const is that its seeking within the sneakers array to see whatever is in the argument is within the array. We then print out both results with seven being found and resulting in true while eight is false. The importance of this is when you're seeking for a specific integer or string within a large array.

With this being the last one for a while talking about array methods I wanted to say thank you again for reading! I’m not the best when it comes to conclusions… so. Keep coding on! Thanks!

--

--

No responses yet