The entries() method of the Set object in JavaScript returns a new iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is similar to the Map object, so that each entry's key is the same as its value for a Set.
The syntax of Set.entries() method is:
entries()
This entries() method of Set returns a new iterator object that contains an array of [value, value] for each element in the Set object, in insertion order. This is similar to the Map object, so that each entry's key is the same as its value for a Set.
Set.entries() returns value of type Iterator
.
In JavaScript, we can use the entries()
method to get an iterator object and use it to iterate over the elements of a Set.
For example,
letters
with initial values 'a', 'b', and 'c'.entries()
method to get an iterator object iterator
for the letters
Set.for...of
loop to iterate over the iterator
and log each entry to the console using console.log()
.const letters = new Set(['a', 'b', 'c']);
const iterator = letters.entries();
for (const entry of iterator) {
console.log(entry);
}
[ 'a', 'a' ] [ 'b', 'b' ] [ 'c', 'c' ]
In JavaScript, we can use the entries()
method to convert a Set object to an array of [value, value] arrays.
For example,
numbers
with initial values 1, 2, and 3.entries()
method to get an iterator object iterator
for the numbers
Set.iterator
to an array using the Array.from()
method and store it in the variable arrayOfEntries
.arrayOfEntries
to the console using console.log()
.const numbers = new Set([1, 2, 3]);
const iterator = numbers.entries();
const arrayOfEntries = Array.from(iterator);
console.log(arrayOfEntries);
[ [ 1, 1 ], [ 2, 2 ], [ 3, 3 ] ]
In JavaScript, we can use the entries()
method to iterate over a Set object containing objects.
For example,
people
with initial objects representing different people.entries()
method to get an iterator object iterator
for the people
Set.for...of
loop to iterate over the iterator
and log each entry to the console using console.log()
.const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const people = new Set([person1, person2]);
const iterator = people.entries();
for (const entry of iterator) {
console.log(entry);
}
[ { name: 'John' }, { name: 'John' } ] [ { name: 'Jane' }, { name: 'Jane' } ]
In this JavaScript tutorial, we learned about entries() method of Set: the syntax and few working examples with output and detailed explanation for each example.