Convert `for` array iterations to array functions
See original GitHub issueFrom Airbnb style guide:
Use
map()/every()/filter()/find()/findIndex()/reduce()/some()/ … to iterate over arrays
const numbers = [1, 2, 3, 4, 5];
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// good
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
sum === 15;
// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) {
increasedByOne.push(numbers[i] + 1);
}
// good
const increasedByOne = [];
numbers.forEach((num) => {
increasedByOne.push(num + 1);
});
// best (keeping it functional)
const increasedByOne = numbers.map(num => num + 1);
Ref: https://github.com/Khan/KaTeX/pull/1469#discussion_r203921764
Issue Analytics
- State:
- Created 5 years ago
- Comments:9 (5 by maintainers)
Top Results From Across the Web
How To Use Array Methods in JavaScript: Iteration Methods
In this tutorial, we will use iteration methods to loop through arrays, perform functions on each item in an array, filter the desired ......
Read more >Array.from() - JavaScript - MDN Web Docs
The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.
Read more >How to Convert Traditional For Loops to JavaScript Array ...
Leverage the some method. As long as at the condition is met once throughout the iterations, it will return true . There is...
Read more >Convert Iterables to Array using Spread | SamanthaMing.com
In JavaScript, we have some built-in iterables that we use spread to convert them to an array: String; Array; Map; Set. There's one...
Read more >JavaScript Array Iteration - W3Schools
Array iteration methods operate on every array item. JavaScript Array forEach(). The forEach() method calls a function (a callback function) once for each...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Things like
filterdon’t work quite as expect if you’re trying to filter out elements of a certain type in the hope that the resultant array will be typed correctly. If you know how to get around this and other similar issues I would be forever grateful.@VinVaz got for it. 😃