How To Get The First Element Of A Set In JavaScript

How to Get the First Element of a Set in JavaScript

This article will show you how to get the first element of a set in JavaScript with three common ways: Using the iterator, destructuring assignment, converting set to array, and using for…of loop. Start reading the detailed article.

How to get the first element of a set in JavaScript

Converting set to array

The easy way is converting the set into the array. Then call the index 0 to get the first element of the array.

Code example:

// Create a new set
const mySet = new Set(['Banana', 'Apple', 'Orange']);

// Convert Set to Array 
const getFirstElement = [...mySet][0];

console.log("My Set is : ", mySet);
console.log('The first element of Set is: ', getFirstElement);

Output:

My Set is :  Set(3) {size: 3, Banana, Apple, Orange}
The first element of Set is:  Banana

Using for…of loop

Using for…of the loop is a very common way to get the first element of a set. We loop into all elements in the set. Then call the first element out.

Example:

// Create a new set
const mySet = new Set(['Banana', 'Apple', 'Orange']);

// Create getFirstElement to return the first item of Set
function getFirstElement(set) {
	for (let element of set) {
		if (element) {
			return element;
		}
	}
	return undefined;
}

console.log("My Set is : ", mySet);
console.log('The first element of Set is: ', getFirstElement(mySet));

Output:

My Set is :  Set(3) {size: 3, Banana, Apple, Orange}
The first element of Set is:  Banana

Destructuring assignment

The next way is destructuring assignment. This is a direct way to get the first element from a set.

Example:

// Create a new set
const mySet = new Set(['Banana', 'Apple', 'Orange']);

// Only get the first item 
const [getFirstElement] = mySet;

console.log("My Set is : ", mySet);
console.log('The first element of the Set is: ', getFirstElement);

Output:

My Set is :  Set(3) {size: 3, Banana, Apple, Orange}
The first element of the Set is:  Banana

Using the iterator

The most practical and elegant solution is using retrieving the first IteratorResult and acquiring its value. We use mySet.keys().next().value.

Example:

// Create a new set
const mySet = new Set(['Banana', 'Apple', 'Orange']);

// Using the iterator 
const getFirstElement = mySet.keys().next().value;

console.log("My Set is : ", mySet);
console.log('The first element of the Set is: ', getFirstElement);

Output:

My Set is :  Set(3) {size: 3, Banana, Apple, Orange}
The first element of the Set is:  Banana

Summary

Hopefully, throughout these ways outlined above. You can easily find for yourself the best way to get the first element of a set in JavaScript. If you have any problems, please comment below. I will answer as possible. Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *