TIL of the Past: 20-10-01
For the Summer Vacation, I have decided to regularly upload the TILs I wrote last year on Notion onto the blog, for recap and archiving purposes.
20.10.01
JS - Advanced Arrays and Objects / ES 7, 8, 10
The lessons for today were so wide spread, starting with the advanced functions and new features of ES5 and ES6, but these were rather similar to the one’s that I have done last month. So it seems appropriate to start with Arrays and Objects.
Advanced Arrays and Objects
array.map, array.filter and array.reduce
I actually studied this in one of the past, but this time around, it was much more compactly and thoroughly introduced.
The general concept of .map
is to loop through every element of the array and apply certain function on each element, and finally, create a new array with the newly created elements. This is the key difference with using .forEach
on an array.
const array = [
{
username: "john",
team: "red",
score: 5,
items: ["ball", "book", "pen"]
},
{
username: "becky",
team: "blue",
score: 10,
items: ["tape", "backpack", "pen"]
},
{
username: "susy",
team: "red",
score: 55,
items: ["ball", "eraser", "pen"]
},
{
username: "tyson",
team: "green",
score: 1,
items: ["book", "pen"]
},
];
// using forEach
const forEachArray = []
array.forEach(user => forEachArray.push(user.username+'!'));
console.log(forEachArray);
// using map
const mapArray = array.map(user => user.username + '?');
console.log(mapArray);
.filter
is used to filter an array under certain condition.
const filterArray = array.filter(user => user.team === "red");
console.log(filterArray);
.reduce
is used mainly to get an accumulated sum of certain element in the array.
I’m not 100% sure why this could be very useful.
const reduceArray = array.reduce((accumulator, user) => {
return accumulator + user.score
}, 0);
console.log(reduceArray);
Class
class Animal {
constructor(name,color) {
this.name = name;
this.color = color;
}
}
class Cow extends Animal {
constructor(name,color){
super(name, color)
}
moo() {
console.log(`Moooo. I'm ${this.name} and I'm ${this.color}`)
}
}
const shelly = new Cow('Shelly', 'black');
Creating a class wasn’t a big problem for me, and I have gone further than this, but using extends
to inherit, and seeing what happens in process was noteworthy.
Newly added feature of the latest ES standards
ES 8
Using padStart
and padEnd
to pad strings
Using the above method, it is possible to add spaces (or strings) in front of or behind the targeted string.
const startLine = ' ||<- Start line';
let turtle = '๐ข';
let rabbit = '๐';
console.log(startLine);
console.log(turtle.padStart(8, '.'));
console.log(rabbit.padStart(8, '.'));
turtle = turtle.trim().padEnd(9, '='); //๐ข=======
Object.values
, .entries
, .keys
The above object methods are used to call certain elements of the object. as the names suggest, the values target the values, keys the keys, and entries target the key and value set.
let obj = {
my: 'name',
is: 'Rudolf',
the: 'raindeer'
}
const introduction = Object.entries(obj).map(entry => entry.join(' ')).join(' ')
console.log(introduction) //'my name is Rudolf the raindeer'
The thing I missed in this solution was actually the .join
function. This is used to join all the elements of the array, and this the parameter is what is used in between when the elements are joined.
ES 10
.flat()
This function is used to flatten the array inside an array. Without any parameters, only one level is flattened, meaning that if there is a array within and array within an array, after using the function only the array within an array part will remain. Using the parameters, it is able to choose how many levels of flattening is desired.
// #1 Turn this array into a new array: [1,2,3,[4],[5]]. Bonus if you can do it on one line
const array = [[1],[2],[3],[[[4]]],[[[5]]]]
console.log(array.flat(2))
.fromEntries()
As practically the exact counterpart as the Object.entries method above, this function turns arrays consisting of key and values to Objects.
//#6 Turn the below users (value is their ID number) into an array:
// [ [ 'user1', 18273 ], [ 'user2', 92833 ], [ 'user3', 90315 ] ]
const users = { user1: 18273, user2: 92833, user3: 90315 };
console.log(Object.entries(users));
//#7 change the output array of the above to have the user's IDs multiplied by 2
// Should output:[ [ 'user1', 36546 ], [ 'user2', 185666 ], [ 'user3', 180630 ] ]
const idTimes2 = Object.entries(users).map(user => [user[0], user[1]*2]);
console.log(idTimes2)
//#8 change the output array of question #7 back into an object with all the users IDs updated to their new version.
// Should output: { user1: 36546, user2: 185666, user3: 180630 }
console.log(Object.fromEntries(idTimes2))