2.1 JavaScript Data Types
# Review
JavaScript Fundamentals - Data Types
The seven "primitive" data types
- number
- bigint
- boolean
- string
- null
- undefined
- symbol
Arrays
Store an ordered collection of values.
# Array methods
- Array.forEach()
- Array.filter()
- Array.find()
- Array.includes()
- Array.indexOf()
- Array.map()
- Array.reduce()
Objects
Store a keyed collection of values.
# Object methods
- Object.keys()
- Object.values()
- Object.entries()
# What is this
?
this
with functions, arrow functions, and lexical scope GIST
# Map and Set
- what
- when
- how
# Map examples
let m = new Map()
m.set(key, value)
m.has(key)
m.get(key)
m.delete(key)
let arrK = m.keys()
let arrV = m.values()
m.clear()
let lenM = m.size
# Set examples
let s = new Set()
s.add(value)
s.has(value)
s.delete(value)
s.clear()
let lenS = s.size
# Practice exercises
- Write a function that will evaluate the given input string and return a new string containing the characters that appear in the source string only once.
Solution Code
function findSingleChars (source) {
const charMap = new Map()
// Iterate over the characters in the source string
for (let char of source) {
// Use the `.get()` method to obtain the current count for the `char`
// If it is not yet in the map, it will return undefined, so set zero
let charCount = charMap.get(char) || 0
// Increment the count for the current `char`
charMap.set(char, ++charCount)
}
// Loop over the members of the `charMap` and if their count is one,
// append them to the `unique` return string.
let unique = ''
charMap.forEach((value, key) => {
if (value === 1) unique += key
})
return unique
}
- Write a function that given a source string, returns a new string containing all of the unique characters which appear in the source string at least once.
Solution Code
function findUniqueCharacters (source) {
const characters = new Set()
// Iterate over the characters in the source string, adding them to the set
for (let char of source) {
characters.add(char)
}
// Copy the members of the set into a new array using the spread operator
// and then join the elements to create a string.
return [...characters].join('')
}
Because the Set()
constructor function can accept any JavaScript iterable object, and strings are iterable, we can pass the source string directly when creating the Set. The above solution can then be done as a one liner arrow function. This time, instead of using the spread operator, use the Array.from() method.
const altSolution = sourceString => Array.from(new Set(sourceString)).join('')
# Before next week
TODO
Start the first hybrid assignment.