How to use Array.prototype.reduce and Symbol.iterator In Javascript
Array.prototype.reduce
is used to build a new array without empty values and implements the Symbol.iterator
method on that array.
Example: The below code implemets the above methods to create a custom iterator that skips empty values.
Javascript
class SkipEmptyValuesIterator { constructor(array) { this .values = array.reduce((acc, value) => { if (value !== '' ) { acc.push(value); } return acc; }, []); } [Symbol.iterator]() { return this .values[Symbol.iterator](); } } const myArray = [ 'cat' , '' , 'ball' , '' , 'cow' ]; const iterator = new SkipEmptyValuesIterator(myArray); for (let value of iterator) { console.log(value); } |
cat ball cow
How to Create Custom Iterator that Skips Empty Value in JavaScript ?
Iterators are important concepts in the world of programming. They allow developers to traverse and manipulate collections of data more efficiently and flexibly. JavaScript, being a high-level programming language, also supports iterators. You can even create a custom iterator that skips the empty values using the below methods:
Table of Content
- Using Generator Function
- Using Array.prototype.filter and Symbol.iterator
- Using Iterator Protocol with Custom Class
- Using Array.prototype.entries and Symbol.iterator
- Using Array.prototype.reduce and Symbol.iterator