// JavaScript Guide and CheatSheet - Ultimate Reference
// By Ahmed Akhtar - Chicago - @Copyright 2023
// From Basic JavaScript to Advanced to Coding Problems!
// Almost Every JavaScript concept is demonstrated below.
// Run this entire code in any JavaScript Compiler!
//Variables in JS
// Global Scope = Yes
// Function Scope = Yes
// Block Scope = No
var variable_js = "variable"
//Let in JS
// Global Scope = No
// Function Scope = Yes
// Block Scope = Yes
let let_js = "let"
//Constants in JS
// Global Scope = No
// Function Scope = Yes
// Block Scope = Yes
const constant_js = "constant"
// (Note var has No Block Scope so var can leak out of blocks,
// such as for loops and if-then statements or {}.
{
var variable_js_test = "variable"
let let_js_test = "let"
const constant_js_test = "constant"
}
// This will run - because var
document.write(variable_js_test + "
")
// This won't run - let
// document.write(let_js_test + "
")
// This won't run - const
// document.write(constant_js_test + "
")
//Strings in JS
var dash = '-'
document.write("Strings in JS:");
document.write("
" + dash.repeat(20) + "
");
// Logs in Console: "Hello World"
console.log("Hello World");
// Prints "Hello World"
document.write("Hello World");
document.write("
");
// JavaScript has 8 Datatypes
// 1. String
// 2. Number
// 3. Bigint
// 4. Boolean
// 5. Undefined
// 6. Null
// 7. Symbol
// 8. Object
//Note:
// Undefined means the variable has been
// declared, but its value has not been assigned.
// Null means an empty value or a blank value.
//String Data Types
var individualName = "ahmed"
document.write(individualName);
// Prints "ahmed"
document.write("
");
// Integer Data Types
var age = 28
// Prints "28"
document.write(age);
document.write("
");
// Boolean Data Types
var smart = true
// Prints true
document.write(smart);
document.write("
");
// Double Data Types
var price = 9.99
// Prints 9.99
document.write(price);
document.write("
" + "
");
document.write("Data Types in JavaScript:")
document.write("
" + dash.repeat(20) + "
");
// Arithemetic in JavaScript
// + Addition
// - Subtraction
// * Multiplication
// ** Exponentiation (ES2016)
// / Division
// % Modulus (Remainder after Divided Quotient)
// ++ Increment
// -- Decrement
// += Add to variable and current
// >= Greater than or equal to
// <= Less than or equal to
// == equal to (only value must match)
// === strict Equals too (value and datatype must match)
// Given a year, return the century it is in.
// The first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.
// For year = 1905, the output should be
// solution(year) = 20;
// For year = 1700, the output should be
// solution(year) = 17.
// Round up in JavaScript
document.write("~Round up: " + Math.ceil(7.1))
document.write("
");
document.write("~Round down: " + Math.floor(7.1))
document.write("
");
// Converting Numbers to Strings
var message = 55
document.write(message.toString())
// Returns '55'
document.write("
");
// Converting Strings to Numbers
var message = '50'
document.write(Number(message));
// Returns 50
document.write("
");
// Converting Strings to Integers
// Note* Also removes any additional text
var size = '20px'
document.write(parseInt(size));
// Returns 20
document.write("
");
// Converting Strings to Floats
// Note* Also removes any additional text
var pi = '3.14pie'
document.write(parseFloat(pi));
// Returns 3.14
document.write("
");
//Checking Data Types
data = 5
document.write(typeof(data))
// Returns Number
document.write("
");
// Left characters of a String
document.write("Left 5 characters")
document.write("
");
var leftstring = "Hello world";
var res = leftstring.substring(0, 5);
document.write(res)
document.write("
" + "
");
document.write("Incrementing in JS")
document.write("
" + dash.repeat(20) + "
");
//Incrementing in JS
let theCount = 2
// Increments next time - Prints 2
document.write(theCount++)
document.write("
");
// Incremented next time - Prints 3
document.write(theCount)
document.write("
");
// Decrements next time - Prints 3
document.write(theCount--)
document.write("
");
// Decremented next time - Prints 2
document.write(theCount)
document.write("
");
// Decrements this time - Prints 1
document.write(--theCount)
document.write("
");
// Increments this time - Prints 2
document.write(++theCount)
document.write("
");
//Minus Assignment Operator
let paycheck = 100
let burger = 5
let money = paycheck
// Returns 100
document.write(money)
document.write("
");
money -= burger
// Returns 95
document.write(money)
document.write("
");
//Addition Assignment Operator
let car_assignment = 4
car_assignment += " Wheel Drive"
// Returns 4 Wheel Drive
document.write(car_assignment)
document.write("
");
// Storing Data
document.write("Arrays, JSON, Sets, Maps:")
document.write("
" + dash.repeat(20) + "
");
// JS Arrays
//Prints Fourth Item in an Array (vegetables[3]) First is 0 in JS
let vegetables = ["Carrots", "Peas", "Lettuce", "Tomatoes"];
document.write("Favorite Vegetable: " + vegetables[3] + "
");
//Returns Favorite Vegetable: Tomatoes
//The join() method returns an array as a string.
let arraycreated = ["s", "t", "r", "i", "n", "g"]
document.write("~Joining Array: " + arraycreated.join(""))
document.write("
");
// First Item of an Array
let firstitemarray = arraycreated[0]
let reversed = arraycreated.reverse()
// Last Item of an Array
let lastitemarray = reversed[0]
// Add to the front of an Array
vegetables.unshift("Cabbage")
document.write(vegetables[0])
//Returns Cabbage (As first item in an Array)
document.write("
");
// Add to the end of an Array
vegetables.push("Potato")
document.write(vegetables[5])
//Returns Potato (As first item in an Array)
document.write("
");
// Add to the end of an Array
document.write("~Does Array include: " + arraycreated.includes("s"))
//Returns True
document.write("
");
// Remove from the front of an Array
vegetables.shift()
document.write("~Remove front array: " + vegetables[0])
// Removes Cabbage at the front of the array. // Returns Carrots
document.write("
");
// Remove from the end of an Array
vegetables.pop()
document.write("~Remove end array: " + vegetables[3])
// Removes Potato at the end of the array. // Returns Tomatoes
document.write("
");
// Combine Arrays - 3 Ways
//Merging Using Concat
let arrayNumbers1 = [1, 2, 3]
let arrayNumbers2 = [4, 5, 6]
let mergeResultConcat = arrayNumbers1.concat(...arrayNumbers2)
document.write("Merging Arrays Concat: " + mergeResultConcat);
//Returns Combined: Array: 1,2,3,4,5,6
document.write("
");
// Combine Arrays - Merging Using Spread Operator
let arrayNumbers3 = [1, 2, 3]
let arrayNumbers4 = [4, 5, 6]
const mergeResult = [...arrayNumbers3, ...arrayNumbers4];
document.write("Merging Arrays Spread Operator: " + mergeResult);
//Returns Combined: Array: 1,2,3,4,5,6
document.write("
");
// Combine Arrays - Merging Using Push
let arrayNumbers5 = [1, 2, 3]
let arrayNumbers6 = [4, 5, 6]
let mergeResultPush = arrayNumbers5
mergeResultPush.push(arrayNumbers6)
document.write("Merging Arrays Push: " + mergeResultPush);
//Returns Combined: Array: 1,2,3,4,5,6
document.write("
");
//Sort Array Text
let unsortedArrayText = ["Apple", "Mango", "Orange", "Grape"]
let sortedArray = unsortedArrayText.sort()
document.write("Sorted Array: " + sortedArray);
//Returns Sorted Array: Apple,Grape,Mango,Orange
document.write("
");
//Sort Array
let unsortedArray2 = [1,9,3,2,0]
document.write("Sorted Array Integers: " + unsortedArray2.sort());
//Returns Sorted Array: 0,1,2,3,9
document.write("
");
let unsortedArray3 = [1,9,3,2,0]
unsortedArray3.sort(function(a, b) {
return a - b;
});
document.write("Sorted Array Integer Function: " + unsortedArray3);
//Returns Sorted Array: 0,1,2,3,9
document.write("
");
//Splice Array
//Splice affeAlterscts original Array
let splicingArray=[1,2,3,4,5];
splicingArray.splice(2);
document.write("
");
document.write(splicingArray);
// Returns 1,2
document.write("
");
//slice
//slice doesn't affect original Array
let slicingArray=[1,2,3,4,5]
slicingArray.slice(2);
document.write(slicingArray);
// Returns 1,2
document.write("
");
//Add to specific Index in an Array.
numbersArray = [1, 2, 3, 4]
numbersArray.splice(2, 0, 99)
// Add at index of 2, remove 0 items, and add 99.
document.write(numbersArray)
document.write("
");
// Returns [1, 2, 99, 3, 4]
//Delete from an Index in an Array.
numbersArray2 = [1, 2, 3, 4]
numbersArray2.splice(2, 1)
// Add at index of 2, remove 0 items
document.write(numbersArray2)
document.write("
");
// Returns [1, 2, 99, 3, 4]
//Turning and Array into a String
let isolated_letters = ['t', 'e', 's']
let letters_joined = isolated_letters.join();
//Regex to replace commas and spaces
letters_joined = letters_joined.replace(/\,/g,'');
// Returns "tes"
// Prints "28"
document.write(letters_joined);
document.write("
");
// JSON - JS Object Notation - JavaScript Objects
var donor2 = {
"name": "John",
"age": 27,
"hobbies": [
"fishing",
"painting",
"coding"]
}
// Accessing variables JSON
//Prints "John likes coding"
document.write(donor2.name
+ " likes " + donor2.hobbies[2] + "
");
// Prints John likes coding
// Alternatively Accessing variables JSON
// Prints "27"
document.write(donor2["age"]);
document.write("
");
// Updating Object Values
// Prints "31"
donor2["age"] = 31
document.write(donor2["age"]);
document.write("
");
// Adding Object Values ("Non existing field/key..")
// Prints "31"
donor2["man"] = "ahmed"
document.write(donor2["man"]);
document.write("
");
// Priting Object Values
// Must parse with JSON.stringify or else will get [Object, Object]
document.write(JSON.stringify(donor2));
document.write("
");
// Nested object
// Note when working with databases it is good to structure your model like this.
// For example you may need to divide notes by notebooks in Database
// Or you might want to divide task lists by category in a Database
const student_object = {
name: 'Ahmed',
age: 33,
subject: {
math: 94,
writing: 50
}
}
// Returns 94
document.write(student_object.subject.math);
document.write("
");
//.Length JavaScript Method
// Prints "# of Hobbies: 3"
document.write("# of Hobbies: " + donor2.hobbies.length);
document.write("
");
//.Length Method Text
// Prints 10
const tenletters = "Tenletters"
document.write(tenletters.length)
document.write("
")
//.Length Method Array
// Prints 4
const countarray = [1, 2, 3, 4]
document.write(countarray.length)
document.write("
")
//.Length Size Method
// Prints 3
const letters = new Set(["a","b","c"]);
document.write(letters.size)
document.write("
")
// Sets
const set1 = new Set([1, 2, 3, 4, 5]);
document.write(set1.has(2));
//Returns true
document.write("
");
//Adding to a Set
set1.add(6)
document.write(...new Set(set1));
document.write("
");
// Returns 123456
//Deleting from a Set
set1.delete(4)
document.write(...new Set(set1));
document.write("
");
//Returns 12356
// Sets Also remove duplicates
const array100 = [1, 2, 2, 3];
var set2 = [...new Set(array100)]
document.write(set2);
//Returns 1,2,3
//Destructuring
document.write("
");
const myString = 'xyz'
const [a,b,c] = myString
document.write(b);
// Returns Y
document.write("
");
// Destructuring Objects
// const cat = {
// name: 'Fluffball',
// breed: 'Calico',
// owner: 'Bob'
// }
// const {name, breed, owner} = cat;
// console.log(owner)
// Destructuring Arrays
const names = ['Jim', 'Joe']
const [name1, name2] = names
document.write(name1)
//Returns Jim
// Temperal Literals
document.write("
");
document.write(`Ahoy there ${name1}!`);
document.write("
" + "
");
document.write("If Else Statements:")
document.write("
" + dash.repeat(20) + "
");
// Time Delays and Repeating functions
// The expression in this
// function happens after 10 seconds
setTimeout(()=>{
console.log("Happened after 10 seconds")
},5000)
// The expression in this
// function happens every 10 seconds endlessly
// setInterval(()=>{
// document.write("Happens every 10 seconds")
// },10)
//If Else Statements
const brave = true
// Returns "You may Enter"
if (brave == true) {
document.write("You may Enter")
}
else if (brave == false) {
document.write("Access Denied");
}
else {
document.write("Nevermind!");
}
document.write("
");
// Pro If Else Statements - "Guard Clauses"
// Cleaner way to write code
// Returns "You may Enter"
function pro_if_else(condition) {
if (condition == null) return
if (condition == true) return `You may Enter`
if (condition == false) return `Access Denied`
return `Nevermind!`
}
document.write(pro_if_else(brave))
document.write("
");
//JavaScript Switch Statements
var strong = true;
// Returns "You'll be Strong"
switch(strong) {
case true:
document.write("You are Strong");
break;
case false:
document.write("You are not Strong");
break;
default:
document.write("Not Sure right now");
}
document.write("
" + "
");
//JavaScript Date and Time
document.write("Date and Time:")
document.write("
" + dash.repeat(20) + "
");
var day
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.write(day); // Returns Current Day
document.write("
" + "
");
document.write("Function/Methods:")
document.write("
" + dash.repeat(20) + "
");
// JavaScript Functions
function firstfunction() {
document.write("My First Function!")
document.write("
");
};
// Calling Function
// Returns "My First Function!"
firstfunction();
// JavaScript Arrow Functions
var add = (num1, num2) => {num1 + num2}
// Returns 5
document.write(add(2, 3));
document.write("
");
// JavaScript Arrow Functions
// Note Curly Braces aren't needed around expression if only one
// Also Note Parenthesis aren't needed around paramter/arg if only one.
var addArrow = num1 => num1 + num1
// Returns 4
document.write("Arrow functions add: " + addArrow(2));
document.write("
");
// Note that where arrow functions really shine are with event handlers
// where the code is just a lot more concise and shorter using arrow functions.
// Consoles "Click" when you click on page
document.addEventListener('click', function() {
console.log("Click")
})
// Note how this looks so much nicer without the entire function word.
// Consoles "Click" when you click on page
document.addEventListener('click', () => {
console.log("Click")
})
// Also note how nice it looks with frontend frameworks.
// onClick={()=> console.log("run function")};
// Class Component. Explained Later
class Car{
constructor(doors){
this.doors = doors;
}
// This will run because arrow function defines
// this keyword from where it was created and not where it was called.
printCarArrow() {
setTimeout(()=>{
console.log(this.doors)
}, 100)
}
// This will NOT run because arrow function defines
// this keyword from where it was created and not where it was called.
printCarFunction() {
setTimeout(function() {
console.log(this.doors)
}, 100)
}
}
let car = new Car(9)
// This will run
// console.logs 9
car.printCarArrow()
// console.logs null
car.printCarFunction()
// This with Arrow functions
// setTimeout(function(){
// console.log("Happened after 10 seconds")
// },5000)
// // This with Arrow functions
// setTimeout(()=>{
// console.log("Happened after 10 seconds")
// },5000)
// Function Return
// Using the Return statement to return a value
function multiply(a, b) {
return a * b;
}
var x = multiply(3, 2);
// Returns 6
document.write(x);
document.write("
");
// JavaScript Arrow Functions - Return
var subtract = (num1, num2) => { return num1 - num2 }
document.write(subtract(10, 3));
// Returns 7
document.write("
");
//JS Alerts (Click Okay)
//alert("Example of 'Alert' Dialog - (Okay)");
//JS Confirm - (Click OK or Cancel)
//var confirm = confirm("Example of 'Confirm' Dialog (Yes or No)");
//document.write("Can you Confirm?: " + confirm);
//document.write("
");
//JS Prompt - (Input Data)
//var prompt = prompt("Example of Prompt Dialog - (Input)");
//document.write("Favorite Movie: " + prompt);
//document.write("
");
document.write("
");
document.write("For Loops:")
document.write("
" + dash.repeat(20) + "
");
// For Loops
for (var i = 0; i < vegetables.length; i++) {
document.write("I love " + vegetables[i] + ", " + "
");
}
// Returns I love Carrots,
// Returns I love Peas,
// Returns I love Lettuce,
// Returns I love Tomatoes,
document.write("For Loop Ended");
// Returns For Loop Ended
document.write("
");
// For Loop (Summing an Array)
var numbers = [20, 40, 30, 10]
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i] //Returns 100
}
// Returns 100
document.write(sum);
document.write("
");
//Function with a For Loop
function logarray(list) {
for (var j = 0; j < vegetables.length; j++) {
document.write(vegetables[j] + ", " + "
");
}
}
logarray(vegetables);
// Returns Carrots,
// Returns Peas,
// Returns Lettuce,
// Returns Tomatoes,
//Hard Loop
for (var i = 0; i < 5; i++) {
document.write("I am " + i + " ");
}
// Returns I am 0
// Returns I am 1
// Returns I am 2
// Returns I am 3
// Returns I am 4
document.write("
" + "
");
document.write("JavaScript Classes and Constructors:")
document.write("
" + dash.repeat(20) + "
");
// Advanced JavaScript
// Classes and Constructors
// Constructors can be used to create objects with properties such as .noise and .raining below:
class Vehicle {
constructor(electric, brand) {
this.electric = electric;
this.brand = brand;
//Methods are functions that are stored as object properties.
// this.makeNoise = function() {
this.printBrand = () => {
document.write(this.brand);
};
}
}
// Settings the variables "dogs" and "cats" to be Monster objects and initializing them with the properties of .raining and .noise
var plane = new Vehicle(true, "Boeing");
var boat = new Vehicle(false, "Yamaha");
// Calling the object's method: makeNoise
// Returns Boeing
plane.printBrand();
document.write("
");
// Returns Yamaha
boat.printBrand();
document.write("
");
// Changing an objects property
boat.brand = "Mitsubishi";
// Returns Mitsubishi
document.write(boat.brand);
document.write("
");
// Adding a Prototype to a class
Vehicle.prototype.color = "White";
console.log(Vehicle.prototype)
// Returns White (Prototype default property)
document.write(boat.color);
document.write("
");
// Adding a method to the constructor function
Vehicle.prototype.showcase = function() {
document.write('presenting: ' + this.color + this.brand);
}
// Returns WhiteMitsubishi
boat.showcase()
document.write("
");
//ES6 Syntax also allows for Template literals, which are a way to output variables in the string, which is popular in other languages such as Ruby
var messageName = 'Ahmed';
var message = `Welcome ${messageName}!`;
// Returns Welcome Ahmed!
document.write(message);
// Using Html Tags with JavaScript
document.write("Center");
document.write("
");
document.write("Filtering Objects in JavaScript:" + "
-----------------
")
// Filtering Objects in JavaScript
var users = {
'friends': [{
'id': 1,
'name': 'George',
'level': 10
}, {
'id': 2,
'name': 'Stacy',
'level': 8
}, {
'id': 3,
'name': 'Fred',
'level': 10
}, {
'id': 4,
'name': 'Amy',
'level': 7
}, {
'id': 5,
'name': 'Bob',
'level': 10
}]
};
var wantedData = users.friends.filter(function(i) {
return i.level === 8;
});
document.write("Filtered Object Data: " + wantedData[0].name);
let array67 = users.friends.map(arr => " " + arr.name)
let result62 = [...new Set(array67)]
document.write(result62);
document.write("
");
const stores = [
{"name":"store1", "turnover": 10000, "location":"WA"},
{"name": "store2", "turnover": 1000, "location":"CA"},
{"name": "store2", "turnover": 1000, "location":"WA"}
]
// Calling Object Field Values:
document.write("Store: " + stores[1].name)
document.write("
");
document.write("Turnover: " + stores[1].turnover)
document.write("
");
document.write("Location: " + stores[1].location)
document.write("
");
// Filtering Objects
// Storing For Loop Values into an Array!
const uniquestates = () => {
let x = 1;
let y = new Array();
let array = stores.map(arr => " " + arr.location)
for (var i = 0; i < array.length; i++) {
y[i]=x;
x++;
var result = [...new Set(array)]
}
document.write(result)
}
uniquestates();
document.write("
");
// Mapping Values into an Array
const pullstates = () => {
let array = stores.map(arr => " " + arr.location)
let result = [...new Set(array)]
document.write(result);
}
pullstates();
document.write("
");
// Adding Object Value Totals
const totalturnover = () => {
let arrayah = stores.map(arr => arr.turnover)
const add = (total, num) => {
return total + num;
}
const resultah = arrayah.reduce(add);
document.write(resultah);
}
totalturnover();
//Returns 12,000
document.write("
");
// Adding Object Value Totals V2
const totalturnover2 = () => {
let arrayah = stores.map(arr => arr.turnover)
const reducer = (accumulator, currentValue) => accumulator + currentValue;
const resultah = arrayah.reduce(reducer);
document.write(resultah);
}
totalturnover2();
//Returns 12,000
document.write("
");
// Adding Filtered Object Value Totals V2
const filteredSum = () => {
var newArray = stores.filter(function (el) {
return el.location == "WA"
});
let arrayah = newArray.map(arr => arr.turnover)
const add = (x, y) => x + y;
let resultah = arrayah.reduce(add);
document.write(resultah);
}
filteredSum()
document.write("
");
//Returns 11,000
// let sum = 0;
// stores.forEach(obj => {
// for (let property in obj) {
// if(property == "turnover")
// sum += obj[property];
// }
// })
// document.write(sum)
// Closures in JavaScript
function outerFunc(outervariable){
return function innerFunc(innervariable){
document.write(outervariable);
document.write("
");
document.write(innervariable);
}
}
const new_function = outerFunc("Outer Var")
console.log("Inner Var")
new_function("Inner Var")
document.write("
" + "
");
document.write("JavaScript Coding Problems" + "
");
document.write("-----------------------------");
document.write("
");
// JavaScript Coding Problem - Last Number
const forwardArray = [1,5,7,9]
let reverseArray = forwardArray.reverse()
document.write(reverseArray)
document.write("
")
document.write(reverseArray[0])
document.write("
")
document.write(forwardArray)
// JavaScript Coding Problem
//Find Username before @ symbol?
let email = "johnny@yahoo.com"
let usernamecount = email.indexOf("@")
let username = email.substring(0, usernamecount)
document.write(username)
document.write("
");
// JavaScript Coding Problem
//Find Vowels using Regex
//Note for mig, M= Multi line, i = case sensitive, g = global search (required)
const findVowels = (str) => {
document.write(str.match(/[aeiou]/mig));
}
findVowels('ahmed'); // 'ae'
document.write("
");
// JavaScript Coding Problem
// Find Count of Vowels
const findVowelsCount = (str) => {
document.write(str.match(/[aeiou]/mig).length);
}
findVowelsCount('ahmed'); // 'ae'
document.write("
");
// JavaScript Coding Problem - Return Duplicates
const yourArray = [1, 1, 2, 3, 4, 5, 5]
const yourArrayWithoutDuplicates = [...new Set(yourArray)]
let duplicates = [...yourArray]
yourArrayWithoutDuplicates.forEach((item) => {
const i = duplicates.indexOf(item)
duplicates = duplicates
.slice(0, i)
.concat(duplicates.slice(i + 1, duplicates.length))
})
document.write(duplicates) //[ 1, 5 ]
document.write("
");
// JavaScript Coding Problem - Return Duplicates 2
let duplicatearray = [1, 9, 2, 5, 5, 3, 3, 8, 4]
let number = 0
var idealduplicates = []
for(var i = 0; i < duplicatearray.length; i++){
for(var j = i + 1; j < duplicatearray.length; j++){
if(duplicatearray[i] == duplicatearray[j]){
idealduplicates.push(duplicatearray[i])
}
}
}
document.write(idealduplicates)
document.write("
");
// JavaScript Coding Problem - Return a Number greater than X
const arr = [56, 34, 2, 7, 76, 4, 45, 3, 3, 34, 23, 2, 56, 5];
const threshold = 40;
const findGreater = (arr, num) => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(arr[i] < num){
continue;
};
res.push(arr[i]);
};
return res;
};
document.write(findGreater(arr, threshold));
document.write("
");
// JavaScript Coding Problem
// TwoSum!!! 2 Numbers that add up to a target
const twoSum = (arr, target) => {
var result = [];
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === target) {
result.push(i);
result.push(j);
}
}
}
return result;
}
// // JavaScript Coding Problem - Ideal TwoSum
var twoSum2 = function(nums, target) {
var results = []
for(var i = 0; i < nums.length; i++){
if(nums[i] + nums[i+1] == target){
results.push(i)
results.push(i + 1)
}
}
return results
}
document.write(twoSum([2, 7, 11, 15], 9));
// => Output [ 0, 1 ]
document.write("
");
// JavaScript Coding Problem - TwoSum third way:
var twoSum3 = function(nums, target) {
let hash = {};
for(let i = 0; i < nums.length; i++) {
const n = nums[i];
if(hash[target - n] !== undefined) {
return [hash[target - n], i];
}
hash[n] = i;
}
return [];
}
document.write("
");
// JavaScript Coding Problem - TwoSum fourth way:
const twoSum_On_Better = (arr, target) => {
let numObject = {};
for (let i = 0; i < arr.length; i++) {
let thisNum = arr[i];
numObject[thisNum] = i;
}
for (var i = 0; i < arr.length; i++) {
let diff = target - arr[i];
if (numObject.hasOwnProperty(diff) && numObject[diff] !== i) {
return [i, numObject[diff]];
}
}
}
document.write(twoSum_On_Better([2, 7, 11, 15, 12, 17], 9));
// Output [ 0, 1 ]
document.write("
");
// JavaScript Coding Problem - Reverse Array
function temporarySwapHalf(array)
{
var left = null;
var right = null;
var length = array.length;
for (left = 0; left < length / 2; left += 1)
{
right = length - 1 - left;
var temporary = array[left];
array[left] = array[right];
array[right] = temporary;
}
return array;
}
document.write(temporarySwapHalf([1,2,3,4]))
document.write("
");
// Return Number Factorial
function factorial(n) {
if(n>=1 && n <=10){
return n * factorial(n-1);
}
return 1
}
document.write(factorial(4))
// Returns 4 * 3 * 2 * 1 = 24
document.write("
");
// HackerRank Climb Stairs. Number of steps - total scenarios to climbing stairs if you can take either 1 or 2 steps.
const climbStairs = (n) => {
//base case
if (n <= 1) return 1;
//otherwise this is basically fib sequence f(n) = f(n-1) + f(n-2)
return climbStairs(n - 1) + climbStairs(n - 2);
};
document.write(climbStairs(4))
document.write("
");
//// JavaScript Coding Problem - Recursion: Fibonacci Numbers
function fibonacci(n) {
let previous = 0;
let current = 1;
if (n < 0 || n === undefined) return null;
if (n < 2) return n;
for (let i = 1; i < n; i++) {
let temp = current;
current = current + previous;
previous = temp;
}
return current;
}
document.write("
");
// JavaScript Coding Problem - Max Difference in an Array
function max_difference(arr) {
var max = -1;
var temp;
for (var i = 0; i < arr.length - 1; i++)
{
temp = Math.abs(arr[i] - arr[i + 1]);
max = Math.max(max, temp);
}
return max;
}
document.write(max_difference([1, 2, 3, 8, 11]))
document.write("
");
// const array2 = [1,2,3,4]
// const reversed = array1.reverse();
// document.write(reversed)
//Maximum Depth Binary Tree
const maxDepth = (root) => {
let maxDepth = 0;
let BFS = (node, level) => {
if(node === null) return
if(level > maxDepth) maxDepth = level
BFS(node.left, level +1)
BFS(node.right, level +1)
}
BFS(root, 1)
return maxDepth
};
//Same Tree Leetcode
//Given the roots of two binary trees p and q, write a function to check if they are the same or not.
const isSameTree = function (p, q) {
if (p === null || q === null) return (p === q);
return ((p.val === q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right));
};
//Symmetric Tree LeetCode
// Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
var isSymmetric = function(root) {
if (!root) return true;
return helper(root.left, root.right);
};
var helper = function (p, q) {
if ((!p && q) || (p && !q) || (p && q && p.val !== q.val)) return false;
if (p && q) return helper(p.left, q.right) && helper(p.right, q.left);
return true;
};
// Hacker Rank Left Rotation Problem
function rotLeft(a, d) {
while (d) {
a.push(a.shift());
d--;
}
return a;
}
// JavaScript Coding Problem - Distinct Pairs
let diffarray = [1, 5, 3, 4, 2, 11, 14, 18, 21, 35, 38, 40, 43]
function distinctPairs(A,k) {
const uniqueValues = new Set(A);
const results = [];
for (num of uniqueValues) {
if (uniqueValues.has(k - num)) {
results.push([num, k - num]);
}
}
return results.length / 2;
}
document.write(distinctPairs(diffarray, 3))
document.write("
");
// JavaScript Coding Problem - Count all pairs
let countAllPairs =[1,2,3,4]
function pairs(arr) {
var res = [],
l = arr.length;
for(var i=0; i" + "TWOSUM with Multiple answers.");
// JavaScript Coding Problem - Distinct Solution:
var artisty =[1, 5, 3, 4, 2]
function distinctPairs(A,k) {
const uniqueValues = new Set(A);
const results = [];
for (num of uniqueValues) {
if (uniqueValues.has(k - num)) {
results.push([num, k - num]);
}
}
return results.length / 2;
}
document.write(distinctPairs(artisty, 3))
document.write("
");
// JavaScript Coding Problem - Largest Double Digit:
function largestdoubledigitarray(nums) {
let results = []
let largest = 0
let secondLargest = 0
for (i = 0; i < nums.length; i++) {
if (nums[i] > largest) {
secondLargest = largest;
largest = nums[i];
continue;
} // End If Statement
} // End for loop
results.push(largest)
results.push(secondLargest)
return results
} // End Function
document.write(largestdoubledigitarray([1, 2, 3, 4]))
// Returns 4, 3 (Largest Possible Number out of String 1234)
document.write("
");
// Find the largest double digit number
// possible from a large number.
function largestdoubledigit(nums) {
let resultsarray = []
let largest = 0
let secondLargest = 0
let str = nums.toString()
for (i = 0; i < str.length; i++) {
if (str[i] > largest) {
secondLargest = largest;
largest = str[i];
continue;
} // End If Statement
} // End for loop
resultsarray.push(largest)
resultsarray.push(secondLargest)
// Turn array into a string and Take out the commas
answer = resultsarray.toString().replace(/[, ]+/g, "").trim();
return answer
} // End Function
document.write(largestdoubledigit([1234]))
// Returns 43 (Largest Possible Number out of String 1234)
// Returns 4 (Largest Possible Number)
document.write("
" + "Largest Number: ");
function largest(nums) {
let results =[]
let largest = 0
for(i=0; i < nums.length; i++) {
if(nums[i] > largest) {
largest = nums[i]
continue;
}
}
return largest
}
document.write(largest([1,2,3,4]))
document.write("
");
// JavaScript Coding Problem Pairs
function pairs2(arr) {
let res = []
for(var i=0; i")
let thecurrentyear = 2023
function solution(year){
document.write("~Find Century" + Math.floor((year-1)/100) + 1);
}
solution(thecurrentyear)
// Is it a Palindrome? The same word backwards and forwards?
function solution(inputString) {
if(inputString == inputString.split("").reverse().join("")){
return true
}
else {
return false
}
}
//Make first letter capital
let word33 = "Word"
const firstLetter = word33.charAt(0)
const firstLetterCap = firstLetter.toUpperCase()
const remainingLetters = word33.slice(1)
const capitalizedWord = firstLetterCap + remainingLetters
// Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
// Example For inputArray = [3, 6, -2, -5, 7, 3], the output should be
// solution(inputArray) = 21.
function solution(inputArray) {
let f, s, arr = []
for(let i=0; i b - a)
return max[0]
}
//Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
//A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below.
function solution(n) {
if(n<0) {
return false
}
return (n*n) + ((n-1)*(n-1))
}
//You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
// Input: word1 = "abc", word2 = "pqr"
// Output: "apbqcr"
var mergeAlternately = function(word1, word2) {
let results = []
if(word1.length > word2.length){
for(var i = 0; i< word1.length; i++){
results.push(word1[i])
results.push(word2[i])
}
}
else{
for(var i = 0; i< word2.length; i++){
results.push(word1[i])
results.push(word2[i])
}
}
return results.join("")
};
// Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size.
// Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1.
// He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.
//Example For statues = [6, 2, 3, 8], the output should be solution(statues) = 3.
// Ratiorg needs statues of sizes 4, 5 and 7.
function solution(statues) {
var smallest = Math.min(...statues)
var largest = Math.max(...statues)
var addstatues = []
for(var i = smallest; i < largest; i++){
if(statues.includes(i)){
continue;
}
addstatues.push(i)
}
addstatues.sort()
return addstatues.length
}
// You are given an array of integers a and an integer k.
// Your task is to calculate the number of ways to pick two different indices i < j,
// such that a[i] + a[j] is divisible by k.
// Example For a = [1, 2, 3, 4, 5] and k = 3, the output should be solution(a, k) = 4.
// There are 4 pairs of numbers that sum to a multiple of k = 3:
// a[0] + a[1] = 1 + 2 = 3
// a[0] + a[4] = 1 + 5 = 6
// a[1] + a[3] = 2 + 4 = 6
// a[3] + a[4] = 4 + 5 = 9
function solution(a, k) {
let results = []
let count = 0
for(var i =0; i < a.length; i++){
for(var j = i + 1; j < a.length; j++){
results.push(a[i] + a[j])
}
}
for(var i =0; i < results.length; i++){
if(results[i] % k == 0){
count++
}
}
return count;
}
// Check array sequence
// Add missing numbers in an array.
let array = [1, 2, 3, 5, 7]
let largestnumber = Math.max(...array)
let smallestnumber = Math.min(...array)
let array2 = []
for(var i = 0; i < largestnumber; i++){
if(!array.includes(i)){
array2.push(i)
// document.write(i + ":")
// document.write(array[i])
}
}
document.write(array2)
//You are given an array of integers a. A new array b is generated by rearranging the elements of a in the following way:
// b[0] is equal to a[0];
// b[1] is equal to the last element of a;
// b[2] is equal to a[1];
// b[3] is equal to the second-last element of a;
// b[4] is equal to a[2];
// b[5] is equal to the third-last element of a; and so on.
// Your task is to determine whether the new array b is sorted in strictly ascending order or not.
let mixedarray = [1, 4, 5, 6, 3]
function solution(a) {
let start = 0
let arrayend = a.length -1
let midpoint = a.length / 2
let results=[]
let increasingsequence = false
for(var i = 0; i < a.length; i++){
if (i < midpoint){
results.push(a[start])
start++
results.push(a[arrayend])
arrayend--
}
}
if(Math.floor(midpoint)")
document.write("
")
for(var i = 0; i < results.length; i++){
document.write(a[i] + " ")
document.write(a[i + 1])
document.write("
")
if(a[i] > a[i+1]){
increasingsequence = false
}
else{
increasingsequence = true
}
}
document.write(increasingsequence)
};
solution(mixedarray)
// Find the number of times a word in an array is part of another word in the array.
let arraycommon = ["back", "backgammon", "front", "frontdoor", "deal", "realdeal" ]
function wordinclude() {
let count = 0
for(var i = 0; i < array.length; i++){
try{
if(array[i+1].includes(array[i])){
count = count + 1
}
}
catch{}
}
document.write(count)
}
wordinclude(arraycommon)