JavaScript – Algorithm (1)

Basic – Syntaxes

What is “truthy”?

if (abc) {
  // This means "abc" NOT empty string, NOT false, NOT 0 (number), NOT null, NOT undefined, NOT NaN
  ...
}

What is the difference between null and undefined?

null
value: null, type: object

undefined
value: null, type: undefined

What’s the difference between || (logical or) and ?? (Nullish Coalescing)?

// "thisThing || thisOtherThing" can be written like this

if (thisThing != 0 && 
    thisThing != undefined && 
    thisThing != false && 
    thisThing != '' && 
    thisThing != null && 
    thisThing != NaN && 
    thisThing != 0n) {
    
    const isThisThing = thisThing; // do stuff with isThisThing;
} 
else {
    const isThisOtherThing = thisOtherThing; // do stuff with isThisOtherThing
}
// "thisThing ?? thisOtherThing" can be written like this

if (thisThing != null && 
    thisThing != undefined) {
	
    const isThisThing = thisThing; // do stuff with isThisThing;
} else {
	
    const isThisOtherThing = thisOtherThing; // do stuff with isThisOtherThing
}

Double exclamation !!

This converts a truthy or falsy value to “true” or “false”

let isIE8 = false; 
isIE8 = !! navigator.userAgent.match(/MSIE 8.0/); 
console.log(isIE8); // returns true or false
  • Falsy values
    • Empty string: ""
    • 0
    • null
    • undefined
    • NaN
  • Truthy values
    • Object: {}
    • Array: []
    • Not empty string: "anything"
    • Number other than zero: 3.14
    • Date: new Date();

Basic – Object & Array

What’s Javascript object

function anObj(ID, value) {
    this._ID = ID;
    this._value = value;
}
const instanceObj = new anObj("1", "value");

const arrObj = [];
arrObj.push(instanceObj);

How to manually put a break point?

debugger

How to check if an object exists in an array (1)?

const arr = [
    {
        id: 1,
        value: 'hi'
    },
    {
        id: 2,
        value: 'hello'
    },
    {
        id: 3,
        value: 'hey'
    },
    {
        id: 4,
        value: 'hello'
    },
]

arr.find(item => item.value === 'hello');
// { id: 2, value: 'hello' }

How to check if an object exists in an array (2)?

const arr = [
    {
        id: 1,
        value: 'hi'
    },
    {
        id: 2,
        value: 'hello'
    },
    {
        id: 3,
        value: 'hey'
    },
    {
        id: 4,
        value: 'hello'
    },
]

arr.filter(item => item.value === 'hello');
// [ { id: 2, value: 'hello' }, { id: 4, value: 'hello' } ]

How to split a string into an array?

var text = 'part1||part2||part3';
var labelArr = text.split('||');

How to extract value of an item property as an array?

let result = arrayObj.map(obj => obj.attr)

How to clone an object into separate object?

let original = [1, 2, 3, 4]
ley copied = [...original]

How to delete an item from array?

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
  return item !== valueToRemove
})
// ["a", "b", "d", "e", "f"]

How to remove last item from array?

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Banana,Orange,Apple

How to get first 10 items from array?

// const data = [{...}, {...}, ...]
const newArray = data.slice(0, 10);

Basic – String

How to replace a string inside a string?

var text = 'abcdef_bdf';
text = text .replace(/b/g, "NEW");

How to check if string start with a text?

var str = “Hello world, welcome to the universe.”;
var n = str.startsWith(“Hello”); // true

How to check if string contains a substring?

'a nice picture'.includes('nice') //true

How to merge 2 arrays?

// 2 Ways to Merge Arrays

const cars = ['🚗', '🚙'];
const trucks = ['🚚', '🚛'];

// Method 1: Concat
const combined1 = [].concat(cars, trucks);

// Method 2: Spread
const combined2 = [...cars, ...trucks];

// Result
// [ '🚗', '🚙', '🚚', '🚛' ]

How to substring a string?

You need to have “start position” and “end position”

var str = "Hello world!";
var res = str.substring(1, 4); // 'ell'
var str = 'my name is maanu.';
console.log(str.slice(-3));     // returns 'nu.' last three
console.log(str.slice(3, -7)); // returns 'name is'
console.log(str.slice(0, -1));  // returns 'my name is maanu'

Replace

let text = someString.replace(/nd|rd|st|th/g, '') // 1st to 1, 2nd to 2, 3rd to 3, 4th to 4

Basic – Useful APIs

forEach, filter, map, reduce/ reduceRight, every/ some

forEach

[2, 5, 9].forEach(function(element, index, array) {
    console.log(index + ":" + element);
    /**
     * 0:2
     * 1:5
     * 2:9
     */
});

filter

var filtered = [12, 5, 8, 130, 44].filter(function(element, index, array) {
    return (element >= 10);
});

console.log(filtered); // [ 12, 130, 44 ]

map

Return new array

var square = [1, 2, 3, 4, 5].map(function(element, index, array) {
    return element * element;
});

console.log(square); // [ 1, 4, 9, 16, 25 ]

reduce

Return one value, “previousValue” is the upcoming result

var total = [0, 1, 2, 3].reduce(function(previousValue, currentValue, index, array) {
    return previousValue + currentValue;
});

console.log(total); // 6

reduceRight

Performed from right to left

var total = [0, 1, 2, 3].reduceRight(function(previousValue, currentValue, index, array) {
    return previousValue + currentValue;
});

console.log(total); // 6

every

// checks whether all elements are >=10
var passed = [12, 54, 18, 130, 44].every(function(element, index, array) {
    return (element >= 10);
});

console.log(passed); // true

some

// checks whether an element is >= 10
passed = [2, 5, 8, 1, 4].some(function(element, index, array) {
    return (element >= 10);
});

console.log(passed); // false

splice

Add or remove item into an array

  • startIndex
    The index where you want to add/remove item
  • deleteCount
    The number of items you want to remove
  • items
    The number you want to add
    (If you’re removing, you can just leave this blank)
const zoo = ['🦊', '🐮'];

zoo.splice(
  zoo.length, // We want add at the END of our array
  0, // We do NOT want to remove any item
  '🐧', '🐦', '🐤', // These are the items we want to add
);

console.log(zoo); // ['🦊', '🐮', '🐧', '🐦', '🐤']

Basic rules

How to skip element inside filter?

Return false will mean those elements won’t be in the new Array, return true means they will

How to stop forEach?

  1. The Ugly Way
    Pass a second argument to forEach to use as context, and store a boolean in there, then use an if.
  2. The Controversial Way
    Surround the whole thing in a try-catch block and throw an exception when you want to break. This looks pretty bad and may affect performance.
  3. The Fun Way: use every()
['a', 'b', 'c'].every(function(element, index) {
  // Do your thing, then:
  if (you_want_to_break) return false
  else return true
})


You can use some() instead, if you’d rather return true to break.

Be the first to comment

Leave a Reply

Your email address will not be published.


*