Converting a Set to an Array is convenient for using array methods that aren't on sets, like filter() or reduce() . The most concise way to convert a Set to an array is using the spread operator as follows.
You Usually Don't Need to Convert a Set to an Array
You may convert sets to arrays for helpers like filter() and map() . But keep in mind that for/of , which we recommend for iterating over an array , also works with sets.
Alternative: Use Array.from()
The spread operator has pretty good browser compability . However, if you need to support older browsers, you may consider using the Array.from() function , which is easier to polyfill.
More Fundamentals Tutorials
- Check if URL Contains a String
Popular examples, reference materials, learn python interactively, js introduction.
- Getting Started
- JS Variables & Constants
- JS console.log
- JS Type Conversions
JS Control Flow
- JS Comparison Operators
- Variable Scope
- JS Multidimensional Array
Exceptions and Modules
- Destructuring Assignment
- Iterators and Iterables
- Data properties
- Accessor properties
Here's an example of data property that we have been using in the previous tutorials.
- get - to define a getter method to get the property value
- set - to define a setter method to set the property value
In the above program, a getter method getName() is created to access the property of an object.
Note: To create a getter method, the get keyword is used.
And also when accessing the value, we access the value as a property.
When you try to access the value as a method, an error occurs.
In the above example, the setter method is used to change the value of an object.
Note: To create a setter method, the set keyword is used.
As shown in the above program, the value of firstName is Monica .
Then the value is changed to Sarah .
Note : Setter must have exactly one formal parameter.
In the above example, Object.defineProperty() is used to access and change the property of an object.
The syntax for using Object.defineProperty() is:
The Object.defineProperty() method takes three arguments.
- The first argument is the objectName.
- The second argument is the name of the property.
- The third argument is an object that describes the property.
Table of Contents
Sorry about that.
Last updated: Dec 29, 2022 Reading time · 5 min
# Table of Contents
- Convert an Array of Objects to a Set
- Add Array of Values to an Existing Set using spread syntax
- Add an Array of Values to an Existing Set using a for...of loop
Use the Set() constructor to convert an array to a Set , e.g. const set = new Set(arr); .
The Set() constructor is used to create Set objects that store unique values of any type.
The Set object only stores unique values. Even if the supplied array contains duplicates, they don't get added to the Set .
The only parameter the Set() constructor takes is an iterable.
If you need to convert the Set back to an array, use the spread syntax (...) .
The spread syntax (...) unpacks the values of the Set into the new array.
You can also use the Array.from() method to convert the Set back to an array.
The Array.from() method creates an array from the provided iterable.
If you need to convert an array of objects to a Set containing only the values of a specific property, use the Array.map() method.
# Convert an Array of Objects to a Set
To convert an Array of objects to a Set :
- Use the Array.map() method to iterate over the array.
- On each iteration, access a specific property and return its value.
- Use the Set() constructor to convert the array to a Set object.
The function we passed to the Array.map() method gets called with each element (object) in the array.
On each iteration, we access the letter property on the object and return the result.
The output of the Array.map() method is an array containing all of the values of the letter property.
The last step is to pass the array of values to the Set() constructor.
# Convert an Array to a Set using Array.forEach()
This is a three-step process:
- Declare a new variable that stores an empty Set object.
- Use the Array.forEach() method to iterate over the array.
- On each iteration, use the Set.add() method to add the element to the Set .
The function we passed to the Array.forEach method gets called with each element in the array.
On each iteration, we use the set.add() method to add the element to a new Set object.
The Set.add method inserts a new element with the supplied value into a Set object, if the value is not already in the Set .
You can also use the Array.reduce() method to convert an array to a Set object.
# Convert an Array to a Set using Array.reduce()
- Use the Array.reduce() method to iterate over the array.
- Initialize the accumulator variable to an empty Set .
- On each iteration, add the element to the Set .
The function we passed to the Array.reduce method gets called for each element in the array.
The initial value of the accumulator variable is an empty Set because that's what we passed as the second argument to the Array.reduce() method.
On each iteration, we use the Set.add() method to add the current element to the Set object.
# Add Array of Values to an Existing Set using spread syntax (...)
- Create a new Set using the Set() constructor.
- Unpack the values of the existing Set and the array into a new Set .
- The new Set will contain the values of the original Set and the array.
We created a new Set using the Set() constructor and used the spread syntax (...) to unpack the values of the existing set and the array into the new Set .
Set objects and arrays are iterable, so we are able to use the spread syntax (...) to unpack them into a new Set .
You can also use a for...of loop to add an array of values to an existing Set .
# Add an Array of Values to an Existing Set using a for...of loop
This is a two-step process:
- Use a for...of loop to iterate over the array.
- Use the Set.add() method to add each array element to the Set object.
The for...of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Convert an Array of Objects to an Array of Values in JS
- Convert Array to String (with and without Commas) in JS
Copyright © 2023 Borislav Hadzhiev
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- English (US)
The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
- If you need the index of the found element in the array, use findIndex() .
- If you need to find the index of a value , use indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)
- If you need to find if a value exists in an array, use includes() . Again, it checks each element for equality with the value instead of using a testing function.
- If you need to find if any element satisfies the provided testing function, use some() .
A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:
The current element being processed in the array.
The index of the current element being processed in the array.
The array find() was called upon.
A value to use as this when executing callbackFn . See iterative methods .
The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
The find() method is an iterative method . It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. find() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, find() returns undefined . Read the iterative methods section for more information about how these methods work in general.
callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined .
The find() method is generic . It only expects the this value to have a length property and integer-keyed properties.
Find an object in an array by one of its properties
Using arrow function and destructuring, find a prime number in an array.
The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number):
Using the third argument of callbackFn
The array argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses filter() to extract the positive values and then uses find() to find the first element that is less than its neighbors.
Using find() on sparse arrays
Empty slots in sparse arrays are visited, and are treated the same as undefined .
Calling find() on non-array objects
The find() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .
- Polyfill of Array.prototype.find in core-js
- Indexed collections guide
- DSA with JS - Self Paced
- A to Z Guide
- Free JS Course
- Cheat Sheet
- Interview Questions
- JS Formatter
- Web Technology
- Explore Our Geeks Community
JS Variables & Datatypes
JS Perfomance & Debugging
- Introduction to ES6
In this article, we will be discussing the Set object provided by ES6. A set is a collection of items that are unique i.e. no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. The set can store any type of value whether primitive or objects.
- it : It is an iterable object whose all elements are added to the new set created, If the parameter is not specified or null is passed then a new set created is empty.
A new set object.
Set.size – It returns the number of elements in the Set.
Methods of Set:
It adds the new element with a specified value at the end of the Set object.
- val: It is a value to be added to the set.
The set object
Example: In this example, we are adding values into the set by using add() method.
It deletes an element with the specified value from the Set object.
- val: It is a value to be deleted from the set.
true if the value is successfully deleted from the set else returns false.
Example: In this example, we are deleting the values into the set by using delete() method.
It removes all the element from the set.
This method does not take any parameter
Example: In this example, we are clearing the values into the set by using clear() method.
It returns an iterator object which contains an array having the entries of the set, in the insertion order.
It returns an iterator object that contains an array of [value, value] for every element of the set, in the insertion order.
Example: In this example, we are using enteries() method.
It returns true if the specified value is present in the Set object.
- val: The value to be searched in the Set
True if the value is present else it returns false.
Example: In this example, we are checking whether the value is present in the set by using has() method.
It returns all the values from the Set in the same insertion order.
An iterator object that contains all the values of the set in the same order as they are inserted.
It also returns all the values from the Set in the insertion order.
Note: It is similar to the values() in the case of Sets
An iterator object that contains all the values of the set in the same order as they are inserted.
Example: In this example, we are printing all the values of the set by using keys() method.
It executes the given function once for every element in the Set, in the insertion order.
- the element key
- the element value
- the Set object to be traversed
- thisargument – Value to be used as this when executing the callback.
It returns a Set iterator function which is values() function by default.
A Set iterator function and it is values() by default.
Example: In this example, we are iterating the values from the set.
Example: In this example, we are checking whether the given subset is present in the given set or not and returning the result according to it.
If an element is present in both Set A and Set B then the union of Set A and B will contain a single copy of the element. Let’s implement and use the union function
Example: In this example, we are merging the two sets.
Example: In this example, we are finding the insersection of two sets.
Example: In this example, we are finding the difference of two sets.
Please Login to comment...
- Web Technologies
Improve your Coding Skills with Practice
On average I work with JSON data 18 times a week. And I still need to google for specific ways to manipulate them almost every time. What if there was an ultimate guide that could always give you the answer?
Creating an object is as simple as this:
This object represents a car. There can be many types and colors of cars, each object then represents a specific car.
Now, most of the time you get data like this from an external service. But sometimes you need to create objects and their arrays manually. Like I did when I was creating this e-shop:
Considering each category list item looks like this in HTML:
I didn't want to have this code repeated 12 times, which would make it unmaintainable.
Creating an array of objects
But let's get back to cars. Let's take a look at this set of cars:
We can represent it as an array this way:
Arrays of objects don't stay the same all the time. We almost always need to manipulate them. So let's take a look at how we can add objects to an already existing array.
Add a new object at the start - Array.unshift
To add an object at the first position, use Array.unshift .
Add a new object at the end - Array.push
To add an object at the last position, use Array.push .
Add a new object in the middle - Array.splice
To add an object in the middle, use Array.splice . This function is very handy as it can also remove items. Watch out for its parameters:
So if we want to add the red Volkswagen Cabrio on the fifth position, we'd use:
Looping through an array of objects
Let me ask you a question here: Why do you want to loop through an array of objects? The reason I'm asking is that the looping is almost never the primary cause of what we want to achieve.
Find an object in an array by its values - Array.find
Let's say we want to find a car that is red. We can use the function Array.find .
This function returns the first matching element:
It's also possible to search for multiple values:
let car = cars.find(car => car.color === "red" && car.type === "cabrio");
In that case we'll get the last car in the list.
Get multiple items from an array that match a condition - Array.filter
The Array.find function returns only one object. If we want to get all red cars, we need to use Array.filter .
Transform objects of an array - Array.map
This is something we need very often. Transform an array of objects into an array of different objects. That's a job for Array.map . Let's say we want to classify our cars into three groups based on their size.
It's also possible to create a new object if we need more values:
Add a property to every object of an array - Array.forEach
But what if we want the car size too? In that case we can enhance the object for a new property size . This is a good use-case for the Array.forEach function.
Sort an array by a property - Array.sort
When we're done with transforming the objects, we usually need to sort them one way or another.
Typically, the sorting is based on a value of a property every object has. We can use the Array.sort function, but we need to provide a function that defines the sorting mechanism.
Let's say we want to sort the cars based on their capacity in descending order.
The Array.sort compares two objects and puts the first object in the second place if the result of the sorting function is positive. So you can look at the sorting function as if it was a question: Should the first object be placed in second place?
Make sure to always add the case for zero when the compared value of both objects is the same to avoid unnecessary swaps.
Checking if objects in array fulfill a condition - Array.every, Array.includes
Array.every and Array.some come handy when we just need to check each object for a specific condition.
Do we have a red cabrio in the list of cars? Are all cars capable of transporting at least 4 people? Or more web-centric: Is there a specific product in the shopping cart?
You may remember the function Array.includes which is similar to Array.some , but works only for primitive types.
In this article, we went through the basic functions that help you create, manipulate, transform, and loop through arrays of objects. They should cover most cases you will stumble upon.
If you have a use-case that requires more advanced functionality, take a look at this detailed guide to arrays or visit the W3 schools reference .
Or get in touch with me and I will prepare another article :-)
Jamstack dev, YouTube video maker & streamer, dev evangelist @Kontent, 3D printing enthusiast, bad AoE2 player, German Shepherd lover
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
The length property returns the length (size) of an array:
The join() method also joins all array elements into a string.
It behaves just like toString() , but in addition you can specify the separator:
Popping and Pushing
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.
The pop() method removes the last element from an array:
The pop() method returns the value that was "popped out":
The push() method adds a new element to an array (at the end):
The push() method returns the new array length:
Shifting is equivalent to popping, but working on the first element instead of the last.
The shift() method removes the first array element and "shifts" all other elements to a lower index.
The shift() method returns the value that was "shifted out":
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
The unshift() method returns the new array length:
Array elements are accessed using their index number :
Array indexes start with 0:
 is the first array element  is the second  is the third ...
The length property provides an easy way to append a new element to an array:
Using delete leaves undefined holes in the array.
Use pop() or shift() instead.
Merging (Concatenating) Arrays
The concat() method creates a new array by merging (concatenating) existing arrays:
Example (Merging Two Arrays)
The concat() method does not change the existing arrays. It always returns a new array.
The concat() method can take any number of array arguments:
Example (Merging Three Arrays)
The concat() method can also take strings as arguments:
Example (Merging an Array with Values)
Flattening an array.
Flattening an array is the process of reducing the dimensionality of an array.
The flat() method creates a new array with sub-array elements concatenated to a specified depth.
Splicing and Slicing Arrays
The splice() method adds new items to an array.
The slice() method slices out a piece of an array.
The splice() method can be used to add new items to an array:
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed .
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added .
The splice() method returns an array with the deleted items:
Using splice() to Remove Elements
With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array:
The first parameter (0) defines the position where new elements should be added (spliced in).
The second parameter (1) defines how many elements should be removed .
The rest of the parameters are omitted. No new elements will be added.
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
The slice() method creates a new array.
The slice() method does not remove any elements from the source array.
This example slices out a part of an array starting from array element 3 ("Apple"):
The slice() method can take two arguments like slice(1, 3) .
The method then selects elements from the start argument, and up to (but not including) the end argument.
If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.
This is always the case when you try to output an array.
These two examples will produce the same result:
Finding Max and Min Values in an Array
You will learn how you solve this problem in the next chapter of this tutorial.
Sorting arrays are covered in the next chapter of this tutorial.
Complete Array Reference
For a complete Array reference, go to our:
The reference contains descriptions and examples of all Array properties and methods.
Test Yourself With Exercises
Use the correct Array method to remove the last item of the fruits array.
Start the Exercise
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top references, top examples, get certified.