Javascript 101 Cheatsheet

Provided is a growing cheatsheet of common Javascript patterns to use when coding transforms:

Working with dates

Getting current date

let date = new Date()

Getting current date minus 7 days

let dateOffset = (24*60*60*1000) * 7; // 7 days
let currentDate = new Date();
currentDate.setTime(currentDate.getTime() - dateOffset);

Converting from unix timestamp to date

let unixTimestamp = 1674005833; // If this is in seconds, multiply by 1000
let currentDate = new Date(unixTimestamp * 1000);
console.log(currentDate.toISOString()) // Tue Jan 17 2023 17:37:13

Converting from string to date

let date = new Date("2015-03-25")
console.log(date.toISOString()) // "2015-03-25T00:00:00.000Z"

Converting date to ISO string

let dateString = new Date("2015-03-25").toISOString()
console.log(dateString) // "2015-03-25T00:00:00.000Z"

Difference between two dates in days

let date1 = new Date("2015-03-27")
let date = new Date("2015-03-25")
let difference = date1 - date
let difference_in_days = difference / (1000 * 3600 * 24);
console.log(difference_in_days) // 2

Working with numbers

Converting string to int

let num = Number.parseInt("1")

Converting string to float

let num = Number.parseFloat("1")

Working with arrays

Looping through an array

let arr = [0, 1, 2];
for (let i = 0; i < arr.length; i++) {
	console.log(i, arr[i])
}

// Same thing but with lambda syntax
arr.forEach((el,idx)=>{
	console.log(idx, el)
})

Mapping an array

let arr = [0, 1, 2];
let squared_arr = arr.map(el=>el*el)

Filtering an array

let arr = [0, 1, 2];
let filtered_arr = arr.filter(el=>el > 1)

Working with dictionaries

Getting an entry in a dictionary

let dict = {"key1": "value1", "key2": "value2", "key 3": "value3"};
let key_3_entry = dict["key 3"] // should evaluate to value3

Getting all the keys from a dictionary

let dict = {"key1": "value1", "key2": "value2", "key 3": "value3"};
let keys = Object.keys(dict) // ["key1", "key2", "key 3"]

Getting all the values from a dictionary

let dict = {"key1": "value1", "key2": "value2", "key 3": "value3"};
let keys = Object.values(dict) // ["value1", "value2", "value3"]

Iterating through a dictionary (key, value)

let dict = {"key1": "value1", "key2": "value2", "key 3": "value3"};
let computed_arr = []
Object.keys(dict).forEach(key=>{
	let value = dict[key];
  computed_arr.push({"key": key, "value": value})
})
console.log(computed_arr)