How to use Array.prototype.entries and Symbol.iterator In Javascript
Array.prototype.entries and Symbol.iterator are used to create a custom iterator class that skips entries with empty values.
Example: The below code shows how to create custom iterator using above-discussed method that skips empty values.
Javascript
class SkipEmptyValues { constructor(array) { this .entries = array.entries(); } [Symbol.iterator]() { return { next: () => { let entry = this .entries.next(); while (!entry.done && entry.value[1] === '' ) { entry = this .entries.next(); } return entry; }, }; } } const myArray = [ 'GFG' , '' , 3, '' , 'JavaScript' ]; const iterator = new SkipEmptyValues(myArray); for (let value of iterator) { console.log(value); } |
Output
[ 0, 'GFG' ] [ 2, 3 ] [ 4, 'JavaScript' ]
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