Definition: An unordered grouping of unique things is called a set. Elements of the set are the objects that are part of the collection.
• Examples:
- The Punjab province’s towns form a set.
Each town in Punjab is part of the set. - The pencils in your purse form a set.
All pencils in your bag are part of the set. - here’s how you can create a Set in both JavaScript and TypeScript:
- JavaScript:
- Sure, here’s how you can create a Set
- JavaScript:
// Creating a set of towns in Punjab
const punjabTowns = new Set();
// Adding elements to the set
punjabTowns.add("Lahore");
punjabTowns.add("Rawalpindi");
punjabTowns.add("Faisalabad");
punjabTowns.add("Multan");// Displaying the set
console.log("Towns in Punjab:", punjabTowns);// Checking if a town is in the setconsole.log("Is Lahore in the set?", punjabTowns.has("Lahore"));
console.log("Is Islamabad in the set?", punjabTowns.has("Islamabad"));// Iterating through the set
console.log("Towns in Punjab:");
punjabTowns.forEach(town => {
console.log(town);
});
Here’s how you can use a Set in a React component:
import React, { useState } from 'react';
function PunjabTowns() {
const [towns, setTowns] = useState(new Set()); const addTown = (town) => {
const updatedTowns = new Set(towns);
updatedTowns.add(town);
setTowns(updatedTowns);
};
return (
<div>
<h2>Towns in Punjab</h2>
<button onClick={() => addTown("Lahore")}>Add Lahore</button>
<button onClick={() => addTown("Rawalpindi")}>Add Rawalpindi</button>
<button onClick={() => addTown("Faisalabad")}>Add Faisalabad</button>
<button onClick={() => addTown("Multan")}>Add Multan</button> <h3>Towns List:</h3>
<ul>
{[...towns].map((town, index) => (
<li key={index}>{town}</li>
))}
</ul>
</div>
);
}export default PunjabTowns;