A JavaScript cheat sheet

1. slice()

The splice() method adds/removes items to/from an array, and returns the removed item(s).

const words: string[] = ['abc', 'xyz', '123', 'the', 'cat', 'sat', 'on', 'the', 'mat'];
const splicedWords = words.splice(3);
console.log('Spliced array: ' + splicedWords);
console.log('Original array: ' + words);

Output:

Spliced array: the,cat,sat,on,the,mat
Original array: abc,xyz,123

Note that on using splice() the original array is impacted.

The contents of the original array can be modified by adding or removing elements too, such as in the following example. Remove the word ‘the’ from the selected index index in the list and insert the words [‘this’, ‘other’] instead:

const words: string[] = ['the', 'cat', 'sat', 'on', 'the', 'mat'];
words.splice(4, 1, 'this', 'other');
console.log('Words: ' + words);

Output:

Words: the,cat,sat,on,this,other,mat

2. map()

Think of map() as a kind of for loop for transforming values.

Some examples of map() can also be found here.

In this example we use map() to create an array of word lengths:

const materials : string[] = [
      'Hydrogen',
      'Helium',
      'Lithium',
      'Beryllium'
    ];

const wordLengths : number[] = materials.map(material => material.length);    
console.log('Word lengths: ' + wordLengths);

Output:

Word lengths: 8,6,7,9

You can use map() to transform values in order to return an array of object literals, such as in this example to return a set of objects containing squares and doubles:

const squaresDoubles = [1, 2, 3, 4, 5].map(val => ({ square: val *  val, double: val * 2}));
console.log(squaresDoubles);

Output:

0: {square: 1, double: 2}
1: {square: 4, double: 4}
2: {square: 9, double: 6}
3: {square: 16, double: 8}
4: {square: 25, double: 10}

Another example of using map() to return an array of object literals containing upper and lower case renditions of words:

var texts = ["aBc", "Xyz"];

var result: { lowercase: string; uppercase: string }[] = texts.map(
  text => ({
   lowercase: text.toLowerCase(),
   uppercase: text.toUpperCase()
  })
);

console.log(result);

Output:

0:
lowercase: "abc"
uppercase: "ABC"
1:
lowercase: "xyz"
uppercase: "XYZ"

3. Correct way of cloning arrays

Use = […myArray]

Arrays in JavaScript are reference values, so when you try to copy it using a simple assignment (‘=’) it copies the reference to the original array and not the value of the array.

To create a real copy of an array, copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.

const array: string[] = ["1", "2", "3", "4"];
const clone1 = array;

console.log(clone1);
console.log(clone1 === array);

const clone2 = [...array];
console.log(clone2);
console.log(clone2 === array);

4. Using object literals

Using object literals in place of switch statements.

Object literals are a great way of replacing switch statements with code looks a lot cleaner and more concise.
A function containing a switch statement to determine a particular outcome might look as follows:

private getChosenValueText(value: string) {
    let returnText: string = "";
    switch (value) {
      case "apples": {
        returnText = "apples chosen";
        break;
      }

      case "oranges": {
        returnText = "oranges chosen";
        break;
      }

      case "pears": {
        returnText = "pears chosen";
        break;
      }
    }

    return returnText;
}

console.log(this.getChosenValueText("apples"));

Output:

apples chosen

Replaced with the more concise object literal:

private getChosenValueTextObjectLiteral(value: string) {
    return {
      apples: "apples chosen",
      oranges: "oranges chosen",
      pears: "pears chosen"
    }[value];
}

console.log(this.getChosenValueTextObjectLiteral("apples"));

Output:

apples chosen

GREAT piece of code to convert an array into a map object:

https://medium.com/dailyjs/rewriting-javascript-converting-an-array-of-objects-to-an-object-ec579cafbfc7

const arrayToObject = (arr: Tab[], keyField: string) =>
      Object.assign({}, ...arr.map(item => ({ [item[keyField]]: item })));
console.log(arrayToObject(tabs, "name"));

Where Tab is a class containing fields “name”, “other”, “offsetWidth”
Output:

{one: Tab, two: Tab, three: Tab}
  one: Tab {offsetWidth: 1, name: "one", other: "one2"}
  three: Tab {offsetWidth: 111, name: "three", other: "three2"}
  two: Tab {offsetWidth: 11, name: "two", other: "two2"}

Iterating over object literals – stack overflow link.

var obj = {
    'foo': 1,
    'bar': 2
};

for (var key in obj) {
    console.log(obj[key]);
}

Output:

1
2

5. Using callbacks

A simple example to execute a function that takes a message string and a callback function as arguments.

The callback function itself can also take arguments using the bind methods:

private doStuff(message: string, callback: (args?: any) => void): void {
    alert(message);
    callback();
}

private alertFinished(message: string): void {
    alert(message);
}

execute(length: number): void {
    this.doStuff(
      "Doing stuff...",
      this.alertFinished.bind(this, "Finished doing stuff")
    );
}

Output:

Doing stuff...
Finished doing stuff.

You can initialise a callback and call it at any time:

callback: (args?: any) => void = () => {
    console.log("Hello");
};

...

someFunction() : void {
   callback();
}

And also the same example but with a string argument passed to it:

callback: (args?: any) => void = val => {
    console.log(val as string);
};

...

someFunction() : void {
   callback('hello');
}

Another example of passing a callback as a function parameter.
This time as a parameter passed to the some() function for determining if an item in a list satifies a logical condition.

const callbackGreaterThanValue : (item: number, value : number) => boolean = 
(item, value) => {
    return item > value;
}

const items : number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9];

console.log(items.some(item => callbackGreaterThanValue(item, 2)) ?
 'Yes' : 'No');
console.log(items.some(item => callbackGreaterThanValue(item, 200)) ?
 'Yes' : 'No');

Output:

Yes
No

6. Template literals (previously Template strings)

Template literals are string literals allowing embedded expressions

Example:

const flag: boolean = true;
console.log(`${flag ? "ON" : "OFF"}`);

Output:

ON

7. Using reduce()

Executes a reducer function that you provide on each array element, resulting in a single output value.

Two different approaches, either using a private function or directly. Both give the same output.

private getSum(total: number, num: number) {
    return total + num;
}

var numbers = [15.5, 2.3, 1.1, 4.7];
const total1 = numbers.reduce(this.getSum, 0);

// total - defaults to zero, num is each value in the array
const total2 = numbers.reduce((total, num) => total + num);

console.log(total1);
console.log(total2);

Output:

23.6
23.6

To find the total of a property within an object array:

const tabs: Tab[] = [new Tab(1), new Tab(11), new Tab(111)];

const totalWidths: number = tabs.reduce(
  (total, tab) => total + tab.offsetWidth,
  0
);

console.log(totalWidths);

Output:

123

8. Using replace()

Pass it an argument representing the string to be replaced, or a regular expression.

Simple replace – replaces 1st occurrence only

console.log("123,321,456,789,456,432".replace(/,/, " "));

Output:

123 321,456,789,456,432

Global replace – all occurrences

console.log("123,321,456,789,456,432".replace(/,/g, " "));

Output:

123 321 456 789 456 432

Global replace – all occurrences, including repeated occurrences

console.log("123,,321,456,789,,,,,456,432".replace(/,+/g, " "));

Output:

123 321 456 789 456 432

Global replace – all words ending with (case insensitive) “at” including whitespaces after it, if any, with an empty string,

const replace: string = "the cAt Sat on the mat".replace(
      /[A-Za-z]at[ ]{0,1}/gi,
      ""
    );

console.log(replace);

Output:

the on the 

9. Using split()

Splits a string into an array of sub-strings using the delimiting string passed to it.

const texts: string[] = "123 345 222 47 999".split(" ");
console.log(texts);

Output:

0: "123"
1: "345"
2: "222"
3: "47"
4: "999"

10. Using repeat()

Builds a new string according to the specified number of copies of the string on which this function has been called.

const text: string = "abracadabra".repeat(2);
console.log(text);

Output:

abracadabraabracadabra

11. Using join()

Joins the elements of an array into a single string. An optional separator string can be used, which if omitted, separates the elements with comma.

const texts: string[] = ["1", "11", "111", "1111", "11111"];
const text: string = texts.join();
console.log(text);

Output:

1,11,111,1111,11111

12. Using filter()

To check if array contains object with specific attribute value:

Hat-tip: https://stackoverflow.com/questions/8217419/how-to-determine-if-javascript-array-contains-an-object-with-an-attribute-that-e

const vendors = [
    {
      Name: 'Jeff',
      ID: 'ABC'
     },
    {
      Name: 'Peter',
      ID: 'DEF'
    } //and so on goes array... 
];

Just use the filter function to obtain those elements matching the attribute value:

vendors.filter(vendor => vendor.Name === "Jeff");

To obtain objects whose ‘name’ property exists in a given string array.

Use the filter function to obtain those elements whose ‘name’ property is included in the ‘maleSet’ string array.

const maleSet : string[] = ['bill', 'john', 'dave'];
const totalSet : { id: string, name: string }[] = [{id: '1', name: 'xyz'}, 
{id : '2', name: 'julie'}, {id: '3', name: 'meghan'}, {id : '4', name: 'bill'}, 
{id: '5', name: 'john'}, {id:'6', name: 'dave'}];

const filteredSet : any = totalSet.filter(item => maleSet.includes(item.name));
console.log(filteredSet)

Output:

[LOG]: [{
  "id": "4",
  "name": "bill"
}, {
  "id": "5",
  "name": "john"
}, {
  "id": "6",
  "name": "dave"
}] 

13. Using some() to test whether at least one element in the array satisfies a boolean condition

In this example we use some() to return if any of the value in the array of numbers is greater than a given value:

const items : number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const hasItems : boolean = hasItemsGreaterThanValue(items, 200);
console.log(hasItems ? 'Yes' : 'No');

function hasItemsGreaterThanValue(items : number[], value: number) : boolean {
  return items.some(item => item > value);
}

Output:

'No'

make money filling out surveys | Harbor touch POS

`