Objects and Associative Arrays
Objects, JSON, AssociativeArrays, Maps and Sets
SoftUni Team
Technical Trainers
Software University
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
SoftUni Code Wizard	http://softuni.bg
Objects,Maps, Sets
https://modshare.futuresight.org/data/icons/project/397.png
http://icons.iconarchive.com/icons/iconshock/real-vista-data/256/objects-icon.png
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Table of Contents
1.Objects and JSON
2.Associative Arrays
3.The Map Class
4.The Set Class
2
http://www.graphicsfuel.com/wp-content/uploads/2012/07/books-icon-512.png
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
3
sli.do#9835
Have a Question?
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Objects in JS
Objects, Properties and JSON
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
5
Objects in JavaScript hold key-value pairs:
Objects in JS
let obj = { name : "SoftUni", age : 3 };let obj = { name : "SoftUni", age : 3 };
console.log(obj); // Object {name: "SoftUni", age: 3}console.log(obj); // Object {name: "SoftUni", age: 3}
obj['site'] "https://softuni.bg";obj['site'] "https://softuni.bg";
obj.age 10;obj.age 10;
obj["name"] "Software University";obj["name"] "Software University";
console.log(obj); // Object {name: "Software University", age: 10,site: "https://softuni.bg"}console.log(obj); // Object {name: "Software University", age: 10,site: "https://softuni.bg"}
delete obj.name; // Delete propertydelete obj.name; // Delete property
obj.site undefined; // Delete property valueobj.site undefined; // Delete property value
console.log(obj); // Object {age: 10, site: undefined}console.log(obj); // Object {age: 10, site: undefined}
http://icons.iconarchive.com/icons/iconshock/real-vista-data/256/objects-icon.png
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
6
More about Objects
let sofia =let sofia =
  name: "Sofia", lat: 42.696552, long: 23.326011 };  name: "Sofia", lat: 42.696552, long: 23.326011 };
console.log(Object.keys(sofia)); // ["name", "lat", "long"]console.log(Object.keys(sofia)); // ["name", "lat", "long"]
let emptyObj };let emptyObj };
console.log(Object.keys(emptyObj)); // []console.log(Object.keys(emptyObj)); // []
console.log(Object.hasOwnProperty('name')); // trueconsole.log(Object.hasOwnProperty('name')); // true
if (sofia.age === undefined)if (sofia.age === undefined)
  console.log("Key 'agedoes not exist");  console.log("Key 'agedoes not exist");
if (sofia.name !== undefined)if (sofia.name !== undefined)
  console.log("Key 'nameexists");  console.log("Key 'nameexists");
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
7
JavaScript objects can be stored as text in JSON format
JSON == JavaScript Object Notation == text object format
Objects and JSON
let obj { name "SoftUni", age };let obj { name "SoftUni", age };
let str JSON.stringify(obj);let str JSON.stringify(obj);
console.log(str); // {"name":"SoftUni","age":3}console.log(str); // {"name":"SoftUni","age":3}
let str "{\"name\":\"Nakov\",\"age\":24}"let str "{\"name\":\"Nakov\",\"age\":24}"
let obj JSON.parse(str);let obj JSON.parse(str);
console.log(obj); // Object {name: "Nakov", age: 24}console.log(obj); // Object {name: "Nakov", age: 24}
https://i1.wp.com/www.alsacreations.com/xmedia/doc/full/json.gif
https://modshare.futuresight.org/data/icons/project/397.png
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Read an array of strings, holding towns with GPS coordinates
Parse each string to JS object (see the below format)
Print the output array of objects as JSON string
8
Problem: Towns to JSON
[{"Town":"Sofia","Latitude":42.696552,"Longitude":23.32601},{"Town":"Beijing","Latitude":39.913818,"Longitude":116.363625}][{"Town":"Sofia","Latitude":42.696552,"Longitude":23.32601},{"Town":"Beijing","Latitude":39.913818,"Longitude":116.363625}]
Town Latitude Longitude |Town Latitude Longitude |
Sofia 42.696552 23.32601 |Sofia 42.696552 23.32601 |
Beijing 39.913818 116.363625 |Beijing 39.913818 116.363625 |
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
9
Solution: Towns to JSON
Check your solution here: https://judge.softuni.bg/Contests/315
function parseTownsToJSON(towns) {function parseTownsToJSON(towns) {
  let townsArr [];  let townsArr [];
  for (let town of towns.slice(1)) {  for (let town of towns.slice(1)) {
    let [empty, townName, lat, lng] =    let [empty, townName, lat, lng] =
      town.split(/\s*\|\s*/);      town.split(/\s*\|\s*/);
    let townObj { Town: townName, Latitude:    let townObj { Town: townName, Latitude:
      Number(lat), Longitude: Number(lng) };      Number(lat), Longitude: Number(lng) };
    townsArr.push(townObj);    townsArr.push(townObj);
  }  }
  return JSON.stringify(townsArr);  return JSON.stringify(townsArr);
}}
parseTownsToJSON(['|Town|Lat|Lng|', '|Sofia |42|23|'])parseTownsToJSON(['|Town|Lat|Lng|', '|Sofia |42|23|'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
10
Nested Objects in JS
let polygon {let polygon {
  about: { name: "triangle", color: "red" },  about: { name: "triangle", color: "red" },
  corners: [{x:2, y:6}{x:3, y:1}{x:-2, y:2}]  corners: [{x:2, y:6}{x:3, y:1}{x:-2, y:2}]
};};
console.log(JSON.stringify(polygon)); //{"about":{"name":"triangle","color":"red"},"corners":[{"x":2,"y":6},{"x":3,"y":1},{"x":-2,"y":2}]}console.log(JSON.stringify(polygon)); //{"about":{"name":"triangle","color":"red"},"corners":[{"x":2,"y":6},{"x":3,"y":1},{"x":-2,"y":2}]}
console.log(polygon.about.color); // redconsole.log(polygon.about.color); // red
polygon.about.location {x:4, y:-7};polygon.about.location {x:4, y:-7};
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Problem: Score to HTML
Read a JSON string, holding array of objects: {name, score}
Print the objects as HTML table like shown below
11
<table><table>
  <tr><th>name</th><th>score</th><tr>  <tr><th>name</th><th>score</th><tr>
  <tr><td>Pesho &amp; Kiro</td><td>479</td></tr>  <tr><td>Pesho &amp; Kiro</td><td>479</td></tr>
  <tr><td>Gosho, Maria &amp; Viki</td><td>205</td></tr>  <tr><td>Gosho, Maria &amp; Viki</td><td>205</td></tr>
</table></table>
[{"name":"Pesho Kiro","score":479},{"name":"Gosho,Maria Viki","score":205}][{"name":"Pesho Kiro","score":479},{"name":"Gosho,Maria Viki","score":205}]
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
12
Solution: Score to HTML
Check your solution here: https://judge.softuni.bg/Contests/315
function scoreToHTMLTable([scoreJSON]{function scoreToHTMLTable([scoreJSON]{
  let html "<table>\n";  let html "<table>\n";
  html += "  <tr><th>name</th><th>score</th>\n";  html += "  <tr><th>name</th><th>score</th>\n";
  let arr JSON.parse(scoreJSON);  let arr JSON.parse(scoreJSON);
  for (let obj of arr)  for (let obj of arr)
    html += `  <tr><td>${htmlEscape(obj['name'])}+    html += `  <tr><td>${htmlEscape(obj['name'])}+
      `</td><td>${obj['score']}</td></tr>\n`;      `</td><td>${obj['score']}</td></tr>\n`;
  return html "</table>";  return html "</table>";
  function htmlEscape(text) // TODO  }  function htmlEscape(text) // TODO  }
}}
scoreToHTMLTable(['[{"name":"Pesho","score":70}]'])scoreToHTMLTable(['[{"name":"Pesho","score":70}]'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Read a JSON string, holding array of JS objects (key / value pairs)
Print the objects as HTML table like shown below
13
Problem: From JSON to HTML Table
<table><table>
  <tr><th>Name</th><th>Price</th></tr>  <tr><th>Name</th><th>Price</th></tr>
  <tr><td>Tomatoes &amp; Chips</td><td>2.35</td></tr>  <tr><td>Tomatoes &amp; Chips</td><td>2.35</td></tr>
  <tr><td>J&amp;B Chocolate</td><td>0.96</td></tr>  <tr><td>J&amp;B Chocolate</td><td>0.96</td></tr>
</table></table>
[{"Name":"Tomatoes Chips","Price":2.35},{"Name":"J&BChocolate","Price":0.96}][{"Name":"Tomatoes Chips","Price":2.35},{"Name":"J&BChocolate","Price":0.96}]
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
14
Solution: From JSON to HTML Table
Check your solution here: https://judge.softuni.bg/Contests/315
function JSONToHTMLTable([json]{function JSONToHTMLTable([json]{
  let html "<table>\n";  let html "<table>\n";
  let arr JSON.parse(json);  let arr JSON.parse(json);
  html += "  <tr>";  html += "  <tr>";
  for (let key of Object.keys(arr[0]))  for (let key of Object.keys(arr[0]))
    html += `<th>${htmlEscape(key)}</th>`;    html += `<th>${htmlEscape(key)}</th>`;
  html += "</tr>\n";  html += "</tr>\n";
  for (let obj of arr) {  for (let obj of arr) {
    // TODO: print obj values in <tr><td>…</td></tr>    // TODO: print obj values in <tr><td>…</td></tr>
  return html "</table>";  return html "</table>";
  function htmlEscape(text) // TODO  }  function htmlEscape(text) // TODO  }
}}
JSONToHTMLTable(['[{"X":5,"Y":7},{"X":2,"Y":4}]'])JSONToHTMLTable(['[{"X":5,"Y":7},{"X":2,"Y":4}]'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Associative Arrays
Objects as Associative Arrays in JS
John SmithJohn Smith
+1-555-8976+1-555-8976
NakovNakov
+359-2-981-9819+359-2-981-9819
Sam DoeSam Doe
+1-555-5030+1-555-5030
key
value
http://findicons.com/files/icons/1233/somatic_rebirth_apps/128/dictionary.png
https://lh5.ggpht.com/EH1sHhtbXtm436L3i6tz5_-j1T-0pCtEh_aQ4ZJjz44Y8xvwVxt4Nl_4HhDU3TYVfOk=h300
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Associative arrays (maps / dictionaries) == arrays indexed by keys
Not by the numbers 0, 1, 2, …
Hold a set of pairs {key  value}, just like JS objects
Associative Arrays (Maps, Dictionaries)
Associative array (dictionary)
John SmithJohn Smith
+1-555-8976+1-555-8976
Lisa SmithLisa Smith
+1-555-1234+1-555-1234
Sam DoeSam Doe
+1-555-5030+1-555-5030
key
value
Traditional array
0         40         4
88
-3-3
1212
408408
3333
key
value
16
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Phonebook – Associative Array Example
let phonebook };let phonebook };
phonebook["John Smith"] "+1-555-8976"; // Addphonebook["John Smith"] "+1-555-8976"; // Add
phonebook["Lisa Smith"] "+1-555-1234";phonebook["Lisa Smith"] "+1-555-1234";
phonebook["Sam Doe"] "+1-555-5030";phonebook["Sam Doe"] "+1-555-5030";
phonebook["Nakov"] "+359-899-555-592";phonebook["Nakov"] "+359-899-555-592";
phonebook["Nakov"] "+359-2-981-9819"; // Replacephonebook["Nakov"] "+359-2-981-9819"; // Replace
delete phonebook["John Smith"]; // Deletedelete phonebook["John Smith"]; // Delete
console.log(Object.keys(phonebook).length); // 3console.log(Object.keys(phonebook).length); // 3
for (let key in phonebook) // Printfor (let key in phonebook) // Print
   console.log(`${key-> ${phonebook[key]}`);   console.log(`${key-> ${phonebook[key]}`);
17
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
18
The order of keys in JS objects is unspecified!
The Order of Keys in JS Object
let obj {let obj {
  "1": 'one',  "1": 'one',
  "3": 'three',  "3": 'three',
  "2": 'two',  "2": 'two',
  "z": 'z',  "z": 'z',
  "a": 'a'  "a": 'a'
}}
console.log(Object.keys(obj)); // ["1", "2", "3", "z", "a"]console.log(Object.keys(obj)); // ["1", "2", "3", "z", "a"]
console.log(obj); // Object {1: "one", 2: "two", 3: "three", z:"z", a: "a"}console.log(obj); // Object {1: "one", 2: "two", 3: "three", z:"z", a: "a"}
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Read towns and incomes (like shown below) and print a JSONobject holding the total income for each town (see below)
19
Problem: Sum by Town
{"Sofia":"25","Varna":"7"}{"Sofia":"25","Varna":"7"}
SofiaSofia
2020
VarnaVarna
33
SofiaSofia
55
VarnaVarna
44
Print the towns in their natural order asobject properties
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
20
Solution: Sum of Towns
Check your solution here: https://judge.softuni.bg/Contests/315
function sumOfTowns(arr{function sumOfTowns(arr{
  let sums {};  let sums {};
  for (let i=0; i<arr.length; i+=2) {  for (let i=0; i<arr.length; i+=2) {
    let [town, income] [arr[i], Number(arr[i+1])];    let [town, income] [arr[i], Number(arr[i+1])];
    if (sums[town] == undefined)    if (sums[town] == undefined)
      sums[town] income;      sums[town] income;
    else    else
      sums[town] += income;      sums[town] += income;
  }  }
  return JSON.stringify(sums);  return JSON.stringify(sums);
}}
sumOfTowns(['Sofia','20', 'Varna','10', 'Sofia','5'])sumOfTowns(['Sofia','20', 'Varna','10', 'Sofia','5'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
21
Write a JS function to count the words in a text (case sensitive)
Words are sequences of lettersdigits and _
The input text comes as array of strings
Return the output as JSON string
Problem: Count Words in a Text
JS devs use Node.js for server-side JS.JS devs use Node.js for server-side JS.
-- JS for devs-- JS for devs
{"JS":3,"devs":2,"use":1,"Node":1,"js":1,"for":2,"server":1,"side":1}{"JS":3,"devs":2,"use":1,"Node":1,"js":1,"for":2,"server":1,"side":1}
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
22
Solution: Count Words in a Text
Check your solution here: https://judge.softuni.bg/Contests/315
function countWords(inputLines{function countWords(inputLines{
  let text inputLines.join('\n');  let text inputLines.join('\n');
  let words text.split(/[^A-Za-z0-9_]+/)  let words text.split(/[^A-Za-z0-9_]+/)
    .filter(w => != '');    .filter(w => != '');
  let wordsCount {};  let wordsCount {};
  for (let of words)  for (let of words)
    wordsCount[w] ? wordsCount[w]++ :    wordsCount[w] ? wordsCount[w]++ :
      wordsCount[w] 1;      wordsCount[w] 1;
  return JSON.stringify(wordsCount);  return JSON.stringify(wordsCount);
}}
countWords(['JS and Node.js', 'JS again and again', 'Oh, JS?'])countWords(['JS and Node.js', 'JS again and again', 'Oh, JS?'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
The Map Class in JS
Key / Value Map
John SmithJohn Smith
+1-555-8976+1-555-8976
NakovNakov
+359-2-981-9819+359-2-981-9819
Sam DoeSam Doe
+1-555-5030+1-555-5030
key
value
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
24
The Map class holdskey  value } map
Better functionality thanplain JS object
The Map Class in JS
let score new Map();let score new Map();
score.set("Peter", 130);score.set("Peter", 130);
score.set("Maria", 85);score.set("Maria", 85);
for (let [k, v] of score)for (let [k, v] of score)
  console.log(k + ' -> ' + v);  console.log(k + ' -> ' + v);
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Phonebook – Map Example
let phonebook new Map();let phonebook new Map();
phonebook.set("John Smith", "+1-555-8976"); // Addphonebook.set("John Smith", "+1-555-8976"); // Add
phonebook.set("Lisa Smith","+1-555-1234");phonebook.set("Lisa Smith","+1-555-1234");
phonebook.set("Sam Doe", "+1-555-5030");phonebook.set("Sam Doe", "+1-555-5030");
phonebook.set("Nakov", "+359-899-555-592");phonebook.set("Nakov", "+359-899-555-592");
phonebook.set("Nakov", "+359-2-981-9819"); // Replacephonebook.set("Nakov", "+359-2-981-9819"); // Replace
phonebook.delete("John Smith"); // Deletephonebook.delete("John Smith"); // Delete
console.log(phonebook.size); // 3console.log(phonebook.size); // 3
for (let [key, value] of phonebook) // Printfor (let [key, value] of phonebook) // Print
   console.log(`${key-> ${value}`);   console.log(`${key-> ${value}`);
25
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
26
Maps Preserve the Insertion Order of Keys
let map new Map([let map new Map([
  ["1", 'one'],  ["1", 'one'],
  ["3", 'three'],  ["3", 'three'],
  ["2", 'two'],  ["2", 'two'],
  ["z", 'z'],  ["z", 'z'],
  ["a", 'a']  ["a", 'a']
]);]);
console.log(map); // Map {"1" => "one", "3" => "three", "2" =>"two", "z" => "z", "a" => "a"}console.log(map); // Map {"1" => "one", "3" => "three", "2" =>"two", "z" => "z", "a" => "a"}
console.log(Array.from(map.keys()));console.log(Array.from(map.keys()));
// ["1", "3", "2", "z", "a"]// ["1", "3", "2", "z", "a"]
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
27
Write a JS function to count the words in a text (case insensitive)
Words are sequences of lettersdigits and _
The input comes as array of strings
Order alphabetically the output words
Problem: Count Words in a Text (with Map)
JS devs use Node.js forserver-side JS.JS devs use Node.js forserver-side JS.
JS devs use JS.JS devs use JS.
-- JS for devs ---- JS for devs --
'devs' -> times'devs' -> times
'for' -> times'for' -> times
'js' -> times'js' -> times
'node' -> times'node' -> times
'server' -> times'server' -> times
'side' -> times'side' -> times
'use' -> times'use' -> times
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
28
Solution: Count Words in a Text (with Map)
Check your solution here: https://judge.softuni.bg/Contests/315
function countWords(inputLines{function countWords(inputLines{
  let words inputLines.join('\n').toLowerCase()  let words inputLines.join('\n').toLowerCase()
    .split(/[^A-Za-z0-9_]+/).filter(w => != '');    .split(/[^A-Za-z0-9_]+/).filter(w => != '');
  let wordsCount new Map();  let wordsCount new Map();
  for (let of words)  for (let of words)
    wordsCount.has(w) wordsCount.set(w,    wordsCount.has(w) wordsCount.set(w,
      wordsCount.get(w)+1) wordsCount.set(w, 1);      wordsCount.get(w)+1) wordsCount.set(w, 1);
  let allWords Array.from(wordsCount.keys()).sort();  let allWords Array.from(wordsCount.keys()).sort();
  allWords.forEach(w =>  allWords.forEach(w =>
    console.log(`'${w}' -> ${wordsCount.get(w)} times`));    console.log(`'${w}' -> ${wordsCount.get(w)} times`));
}}
countWords(['JS and Node.js', 'JS again and again', 'Oh, JS?'])countWords(['JS and Node.js', 'JS again and again', 'Oh, JS?'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Read towns and population (like shown below) and print a thetowns and their total population for each town (see below)
Print the towns in the order of their first appearance
29
Problem: Population in Towns
Varna <-> 40000Varna <-> 40000
Sofia <-> 1200000Sofia <-> 1200000
Plovdiv <-> 20000Plovdiv <-> 20000
Sofia <-> 100000Sofia <-> 100000
Varna <-> 420000Varna <-> 420000
Plovdiv <-> 400000Plovdiv <-> 400000
Plovdiv <-> 50000Plovdiv <-> 50000
Varna 460000Varna 460000
Sofia 1300000Sofia 1300000
Plovdiv 470000Plovdiv 470000
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
30
Solution: Population in Towns
Check your solution here: https://judge.softuni.bg/Contests/315
function populationInTowns(dataRows{function populationInTowns(dataRows{
  let total new Map();  let total new Map();
  for (let dataRow of dataRows) {  for (let dataRow of dataRows) {
    let [town, population] dataRow.split(/\s*<->\s*/);    let [town, population] dataRow.split(/\s*<->\s*/);
    population Number(population);    population Number(population);
    if (total.has(town))    if (total.has(town))
      total.set(town, total.get(town) population);      total.set(town, total.get(town) population);
    else total.set(town, population);    else total.set(town, population);
  }  }
  for (let [town, sum] of total)  for (let [town, sum] of total)
    console.log(town sum);    console.log(town sum);
}}
populationInTowns(['B<->20', 'A<->30', 'B<->5'])populationInTowns(['B<->20', 'A<->30', 'B<->5'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Read sales data in the following format
Print for each town the sum of incomes for each product
Order the towns and product as they first appear
31
Problem: City Markets
Sofia -> Laptops HP -> 200 2000Sofia -> Laptops HP -> 200 2000
Sofia -> Raspberry -> 200000 1500Sofia -> Raspberry -> 200000 1500
Montana -> Oranges -> 200000 1Montana -> Oranges -> 200000 1
Montana -> Cherries -> 1000 0.3Montana -> Cherries -> 1000 0.3
Sofia -> Audi Q7 -> 200 100000Sofia -> Audi Q7 -> 200 100000
{town} -> {product} -> {amountOfSales}:{priceForOneUnit}{town} -> {product} -> {amountOfSales}:{priceForOneUnit}
Town SofiaTown Sofia
$$$Laptops HP 400000$$$Laptops HP 400000
$$$Raspberry 300000000$$$Raspberry 300000000
$$$Audi Q7 20000000$$$Audi Q7 20000000
Town MontanaTown Montana
$$$Oranges 200000$$$Oranges 200000
$$$Cherries 4000$$$Cherries 4000
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
32
Solution: City Markets (Nested Maps)
function cityMarkets(sales) {function cityMarkets(sales) {
  let townsWithProducts new Map();  let townsWithProducts new Map();
  for (let sale of sales) {  for (let sale of sales) {
    let [town, product, quantityPrice] = sale.split(/\s*->\s*/);    let [town, product, quantityPrice] = sale.split(/\s*->\s*/);
    let [quantity, price] quantityPrice.split(/\s*:\s*/);    let [quantity, price] quantityPrice.split(/\s*:\s*/);
    if (!townsWithProducts.has(town))    if (!townsWithProducts.has(town))
      townsWithProducts.set(town, new Map());      townsWithProducts.set(town, new Map());
    let income quantity price;    let income quantity price;
    let oldIncome townsWithProducts.get(town).get(product);    let oldIncome townsWithProducts.get(town).get(product);
    if (oldIncome) income += oldIncome;    if (oldIncome) income += oldIncome;
    townsWithProducts.get(town).set(product, income);    townsWithProducts.get(town).set(product, income);
  }  }
  // TODO: print the incomes by towns and products  // TODO: print the incomes by towns and products
}}
Check your solution here: https://judge.softuni.bg/Contests/315
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
The Set Class in JS
Set of Unique Values of Any Type
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
34
Sets in JS are collections of unique objects
The insertion order is preserved, with no duplicates
The Set Class in JS
let names new Set();let names new Set();
names.add("Peter"); names.add(20);names.add("Peter"); names.add(20);
names.add("Maria"); names.add(5);names.add("Maria"); names.add(5);
console.log(names.has('Peter')); // trueconsole.log(names.has('Peter')); // true
names.add("Maria"); // Duplicates are skippednames.add("Maria"); // Duplicates are skipped
names.delete(20); // Delete element if existsnames.delete(20); // Delete element if exists
for (let name of names) console.log(name);for (let name of names) console.log(name);
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
35
Write a JS function to extract all unique words from a text (caseinsensitive)
Words are sequences of lettersdigits and _
The input comes as array of strings
The output should hold the words in their order of appearance
Problem: Extract Unique Words
JS devs use Node.js forserver-side JS.JS devs use Node.js forserver-side JS.
JS devs use JS.JS devs use JS.
-- JS for devs ---- JS for devs --
js, devs, use,node, for, server,sidejs, devs, use,node, for, server,side
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
36
Solution: Extract Unique Words
Check your solution here: https://judge.softuni.bg/Contests/315
function extractWords(inputSentences) {function extractWords(inputSentences) {
  let wordPattern /\b[a-zA-Z0-9_]+\b/g;  let wordPattern /\b[a-zA-Z0-9_]+\b/g;
  let words new Set();  let words new Set();
  for (let sentence of inputSentences) {  for (let sentence of inputSentences) {
    let matches sentence.match(wordPattern);    let matches sentence.match(wordPattern);
    matches.forEach(x=>words.add(x.toLowerCase()));    matches.forEach(x=>words.add(x.toLowerCase()));
  }  }
  console.log([...words.values()].join(", "));  console.log([...words.values()].join(", "));
}}
extractWords(['JS and Node.js', 'JS again and again', 'Oh, JS?'])extractWords(['JS and Node.js', 'JS again and again', 'Oh, JS?'])
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
Practice: Using Objects, Maps, Sets
Live Exercises in Class (Lab)
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
38
Objects in JS hold key-value pairs
Maps map keys to values, preserve keys order
Sets hold unique collection of values
Summary
C:\Users\Ivan\Desktop\elements_presentations\summary_pic.png
let obj = { name : "SoftUni", age : 3 };let obj = { name : "SoftUni", age : 3 };
obj.age++;obj.age++;
obj[town] 'Sofia';obj[town] 'Sofia';
delete obj.name;delete obj.name;
let map new Map();let map new Map();
map.set('score', 20);map.set('score', 20);
let map new Set(); set.add(5);let map new Set(); set.add(5);
D:\_WORK PROJECTS\Nakov\Presentation Slides Design\STORE\Software University Foundation Logo BG and ENG black WHITOUT background CMYK.png
License
This course (slides, examples, demos, videos, homework, etc.)is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license
40
Free Trainings @ Software University
Software University Foundation – softuni.org
Software University – High-Quality Education,Profession and Job for Software Developers
Software University @ Facebook
Software University @ YouTube
Software University Forums – forum.softuni.bg
Software University
Software University Foundation
Software University @ Facebook
Software University Videos @ YouTube
Software University - Forum