• JavaScript Video Tutorials

JavaScript - Set.entries() Method



The Set.entries() method in JavaScript will return a new iterator object that contains an array of [value, value] pairs of each element in the Set object, in insertion order.

Syntax

Following is the syntax of JavaScript Set.entries() method −

entries()

Parameters

This method does not accept any parameters.

Return value

This method returns a new iterable iterator object.

Examples

Example 1

In the following example, the entries() method returns an iterator, and the for...of loop iterates through the entries and prints them.

<html>
<body>
   <script>
      const mySet = new Set(["One", "Two", "Three"]);
      const iterator = mySet.entries();

      for (const entry of iterator) {
         document.write(`Result: ${[...entry]} <br>`);
      }
   </script>
</body>
</html>

If we execute the above program, the iterator object contains an array of same value for both key and value.

Example 2

In this example, a Set is created with duplicate and unique numbers. The entries() method returns an iterator, and the spread operator is used to convert the iterator to an array of unique [value, value] pairs, discarding duplicates.

<html>
<body>
   <script>
      const uniqueNumbers = new Set([1, 2, 3, 2, 4, 5]);
      const uniqueEntries = uniqueNumbers.entries();
      document.write([...uniqueEntries]);
   </script>
</body>
</html>

As we can see the output, an array of unique [value, value] pairs will be returned.

Example 3

Here, we are using the next() method to retrieve the first entry, which is an array with the elements as both key and value.

<html>
<body>
   <script>
      const colors = new Set(['red', 'green', 'blue']);
      const entries = colors.entries();
      document.write(entries.next().value, "<br>");
      document.write(entries.next().value, "<br>");
      document.write(entries.next().value);
   </script>
</body>
</html>

If we execute the program, it returns the [value, value] pairs.

Advertisements