New Javascript Set

| | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

How to use sets in JavaScript

Do you have a list of data that should only contain unique values ? This is where the JavaScript Set data type really shines. It is a new type of object that allows you to create a collection of unique values; no duplicates are allowed in a set.

In this guide, we’ll talk about what sets are, how they work, and when they can be useful. We will see some examples of each of the Set methods available in JavaScript.

What is a set?

A set is a collection of values ‚Äã‚Äãthat cannot contain duplicates. This data type was introduced in ECMAScript 6. In particular, sets are a feature of many other programming languages.

Lists are useful because they allow you to store multiple values. Lists support storing duplicate values, which can be useful in a myriad of scenarios.

For example, if you are archiving a list of coffee shop orders, you will need to be able to store duplicate values. Two customers can order the same drink.

In some cases you may want to store only unique values ‚Äã‚Äãin a list. This is where you want to use the Set object. The values in the sets can appear only once.

In JavaScript, a set is declared like any other object. Let’s create a Set that stores a list of favorite cakes reported by customers at a local tearoom:

Our code returns: Set []. We just created a set. It has no value at the moment, as you can see from the output of our code ; we’ll add them later.

Start default set Values ‚Äã‚Äã

Sets can be initialized from of an array, string, or other iterable. This is useful because it means that you don’t need to manually add values ‚Äã‚Äãto your Set; you can work from existing ones.

Consider the following list:

These values ‚Äã‚Äãare currently stored in an array. To convert them to Set, we can pass our array when creating a new Set object:

Our code returns:

Adding values to a set

The Ensembl object e comes with a method called add () which makes it easy to add items to a set. The name of the method used to add an element to a set is even easy to remember: add ().

Let’s say we want to add "Boston Cream Pie" to our list of cakes that are sold at a local bakery. We use the add () method to add this value:

Our code returns:

Our set now contains four objects. If you try to add an object that is already in a set, that object will not be added. Sets cannot store duplicate values.

Check if a value exists in a set

We need to check if "Boston Cream Pie" is in our cake list. It was a new addition to the cake list and the baker wants to verify that we added it.

This is where the has () method comes in. The has () method allows you to check if a Set has a particular value. Once again, the method has an easy name to remember !

Consider the following code:

Our code returns: true. The has () method returns a Boolean value, true or false, depending on whether a Set contains a particular value. This method is similar to includes () that you would use on an array but has () only works with Sets.

Remove a value from a set

The baker has decided that strawberry cheesecakes will no longer be served in the bakery. The strawberry cheesecake took longer than the other cakes and was not very popular.

You can delete a value from a set using the appropriate delete () method. Let’s remove the " Strawberry Cheesecake" value from our set:

Our code returns:

Strawberry Cheesecake has been removed from our set.

You can remove all values ‚Äã‚Äãfrom a set using the clear () method.

Iterate over a set

Sets, like lists, are iterable objects. You know what that means - you can browse them.

We’re going to use a for-each loop to cycle through our cake set. Our for-each loop will look at every item in our list - for every item in the list - and output it to the console:

Our code returns an iterator that prints each value of our Set to the console:

C ’ is that simple ! for-of loop:

This code returns the same output as our forEach loop:

You can choose to use a for loop to browse a set ble, but because sets are iterable or ggetti, it is easier to use a for-each or a for-of loop .

Removing duplicate values ‚Äã‚Äãusing Set

When you initialize a Set with an array, all duplicate values ‚Äã‚Äãwill be automatically removed. It’s an incredibly useful feature.

Let’s say we have a list that contains a number of cake orders:

This set contains all cake orders made at the bakery. In total, there are eight values; two values ‚Äã‚Äãare duplicated.

Suppose the baker wants to know what types of pies have been ordered, so he can start cooking his own kitchen. We could find out by converting our Set to a list:

Our code returns:

Our list was reduced to six values. These are all unique values ‚Äã‚Äãon our order list. There is one step left.

We need to convert our cake set back to a list so that we can interact with it using standard list methods. We can then do this using the Array.from () method:

Our code returns:

While the output of this code is similar to our Set, there is one big difference: our data is now stored as an array. This means that we can interact with it using all of the built-in JavaScript array methods.

Conclusion

The Set object allows you to store a list of items that can only contain single valued items. Sets can be initialized from an existing iterable object, such as a list or a string.

Since the Set object removes duplicate values, you can use it as a way to remove duplicates from an array. Then, when finished, you can convert your Set back to a table.

You are now ready to start using Sets in JavaScript like a pro!

👻 Read also: what is the best laptop for engineering students?

New Javascript Set __del__: Questions

__del__

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

New Javascript Set __del__: Questions

__del__

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

2639

Answer #2


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

2639

Answer #3

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

RESPECTIVE OUTPUT

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

__delete__

Is there a simple way to delete a list element by value?

5 answers

I want to remove a value from a list if it exists in the list (which it may not).

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

The above case (in which it does not exist) shows the following error:

Traceback (most recent call last):
  File "D:zjm_codea.py", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list

So I have to do this:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

But is there not a simpler way to do this?

1055

Answer #1

To remove an element"s first occurrence in a list, simply use list.remove:

>>> a = ["a", "b", "c", "d"]
>>> a.remove("b")
>>> print(a)
["a", "c", "d"]

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]

We hope this article has helped you to resolve the problem. Apart from New Javascript Set, check other __del__-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Manuel Wu

Warsaw | 2022-12-10

Thanks for explaining! I was stuck with New Javascript Set for some hours, finally got it done 🤗. I am just not quite sure it is the best method

Carlo Williams

Vigrinia | 2022-12-10

Thanks for explaining! I was stuck with New Javascript Set for some hours, finally got it done 🤗. Will use it in my bachelor thesis

Chen Galleotti

New York | 2022-12-10

Simply put and clear. Thank you for sharing. New Javascript Set and other issues with ones was always my weak point 😁. I just hope that will not emerge anymore

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically