![]() |
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 FunctionThe generator function can be used to yield non-empty values which can be further used to create a custom iterator that skips empty values. Syntax:// Generator function Example: The below code explains the use of generator function to create custom iterator that skips empty values. Javascript
Output
GFG 3 JavaScript Using Array.prototype.filter and Symbol.iteratorA custom iterator class that filters out empty values using Syntax:array.filter(value => value !== '')[Symbol.iterator]();
Example: The below code illustrates the use of the filter() method to create a custom iterator that skips empty values. Javascript
Output
GFG 3 JavaScript Using Iterator Protocol with Custom ClassThe iterator protocol is implemented using a custom class, which is used to iterate over the array and skipping empty values by controlling the Example: The below code is practical implementation of the above-discussed approach to create iterator. Javascript
Output
GFG 3 JavaScript Using Array.prototype.entries and Symbol.iteratorArray.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
Output
[ 0, 'GFG' ] [ 2, 3 ] [ 4, 'JavaScript' ] Using Array.prototype.reduce and Symbol.iterator
Example: The below code implemets the above methods to create a custom iterator that skips empty values. Javascript
Output
cat ball cow |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |