1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
Set, a Javascript data structure, is a collection of unique values, providing a powerful tool for scenarios where distinct elements matter. But how do you iterate on a Javascript Set? In this blogpost, you will explore code samples to iterate set in Javascript, common errors, and a fun coding problem to polish your skills.
forEach()
to iterate JS setThe forEach()
method executes a provided function once for each element in the Set.
const mySet = new Set([1, 2, 3, 4]);
mySet.forEach(element => {
console.log(element);
});
for...of
LoopClassic for loop over Set elements:
const mySet = new Set(['apple', 'orange', 'banana']);
for (const element of mySet) {
console.log(element);
}
The spread operator allows you to convert a Set to an array, enabling array methods for iteration.
const mySet = new Set([1, 2, 3]);
const setArray = [...mySet];
setArray.forEach(element => {
console.log(element);
});
Array.from()
The Array.from()
method creates a new, shallow-copied array from an iterable object like a Set.
const mySet = new Set([10, 20, 30]);
const setArray = Array.from(mySet);
setArray.forEach(element => {
console.log(element);
});
The entries()
method returns an iterable of Set entries, allowing you to destructure key-value pairs.
const mySet = new Set(['red', 'green', 'blue']);
for (const [index, color] of mySet.entries()) {
console.log(`Color at index ${index}: ${color}`);
}
If the Set is not initialized (undefined), using forEach()
will result in an error. Ensure proper initialization.
let mySet; // Set not initialized
try {
mySet.forEach(element => {
console.log(element);
});
} catch (error) {
console.error("Error:", error.message);
}
Unlike other loops, the break
statement is not available in functions passed to Set.forEach()
. Be cautious with control flow statements.
const mySet = new Set([10, 20, 30]);
// Error: The 'break' statement is not available in the function passed to Set.forEach()
mySet.forEach(element => {
if (element === 20) {
break;
// β SyntaxError: Illegal break statement
}
console.log(element);
});
In the spirit of Test Driven Development ( π), lets test our understanding by solving a problem.
Write a function
setExplorer(set)
that takes a Set and returns an array containing the square of each element in the Set.
Problem (JavaScript)
/**
* Explore the elements of a Set and return an array with the square of each element.
*
* @param {Set} set - The Set to explore.
* @returns {Array} - An array containing the square of each element.
*/
function setExplorer(set) {
// > > > π Write code here π < < <
}
// Driver code
const myNumberSet = new Set([2, 4, 6, 8]);
console.log(setExplorer(myNumberSet));
// Expected Output: [4, 16, 36, 64]
Please attempt before seeing the Answer:
function setExplorer(set) {
// Using Array.from() to create an array
// and map to square each element
return Array.from(set, element => element * element);
}
Explanation:
setExplorer
function uses Array.from()
to convert the Set to an array.map
function is then applied to square each element in the array.May your Sets are always iterable now! π
Feel free to reach out!