"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Day / Days of Code: Iterating with Methods

Day / Days of Code: Iterating with Methods

Published on 2024-11-02
Browse:199

Day /  Days of Code: Iterating with Methods

Thu, September 5, 2024

Hello everyone! ?

Iterators are yet another JavaScript power tool. In a slight twist, while today’s assignment is named Iterators: .forEach(), .map(), .findIndex(), .filter(), and .reduce(), to be transparent, these are methods that employ iterators to accomplish their purpose.

Iterator Methods Overview
.forEach(): Iterates elements & performs the provided function
.map(): Iterates elements & applies function to create a new array
.findIndex(): Iterates elements, finds match & returns the index
.reduce(): Iterates elements & accumulates values, summation
.filter(): Iterates elements & conditionally creates new array
These methods belong to the Array prototype object and abstract the mundane iterative process to directly expose the data.

Favorite Iterator of the Day: .filter()
After exploring and experimenting with these iterators today, I found that my favorite is .filter() because of its extensibility. A little bit like a factory function, it can be used to create new objects, as long as they’re subsets of the object matching a condition, such as all elements over a certain amount:

const bigNumbers = [148, 256, 384, 918, 512];

// Using filter() to get all elements above 200
const allAbove200 = bigNumbers.filter(num => num > 200);

console.log(allAbove200); // Output: [256, 384, 918, 512]

That’s so sleek and streamlined that it’s almost beautiful.

Happy coding! ?

Release Statement This article is reproduced at: https://dev.to/jacobsternx/day-67-100-days-of-code-iterating-with-methods-41hc?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3