Cleaning Up the Tags With a Set
In this lesson, you cleaned up order 1042’s tags, ["gift", "fragile", "gift"], with a JavaScript
Set.
- JavaScript has a
Settype too. You make one with thenewkeyword, as you make aMap, and like Python’sset(), it takes an iterable:new Set(order.tags)builds it from the tags array and drops the repeat. - For the length, a Set has a
.sizeproperty, where Python haslen(). A Set isn’t an array, sotags.lengthgivesundefined. - A Set keeps its members in the order they first arrived, so JavaScript logs
Set(2) { 'gift', 'fragile' } 2. The number in parentheses is the size, and the braces hold the members: that’s how a Set prints, not code you write. - Python’s set promises no order. For strings like these, its order can change from run to run:
one run printed
{'fragile', 'gift'} 2, and the next printed{'gift', 'fragile'} 2. - Because a Set keeps the order,
[...new Set(order.tags)]removes the repeats and gives[ 'gift', 'fragile' ]. The...spreads the Set into a new array, as it spreads one array into another. In Python, keeping the order takeslist(dict.fromkeys(order["tags"])), because a dict keeps its keys in the order they arrived, as a Set does with its members. tags.has("gift")does the job of Python’s"gift" in tags, and logstrue.- Watch out for porting
inas it reads: JavaScript’sinasks whether an object has a key by that name, as it does for an array’s positions, so"gift" in tagsisfalse. .add()adds a member, as in Python, and adding"gift"again leaves the size at 2. Where Python hasdiscard(), a Set has a.delete()method, a call on the Set, not thedeleteoperator you used on object keys.- Watch out for Python’s set literal: in JavaScript, braces make an object, which needs keys and
values, so
{"US", "CA", "AU"}ported with its braces stops the file with a syntax error. JavaScript has no Set literal, so pass the items as an array:new Set(["US", "CA", "AU"]). - Combining sets, such as a union, comes later.
Here’s Marta’s Python step:
order = {"tags": ["gift", "fragile", "gift"]}
country = "GB"
TRACKED_COUNTRIES = {"US", "CA", "AU"}
tags = set(order["tags"])
print(tags, len(tags))
print("gift" in tags)
print(country in TRACKED_COUNTRIES)