JavaScript

Last Updated: 12/22/2022

Array

Using literal

const cars = ["honda", "toyota"];

Using Array Function

const cars = new Array("honda", "toyota")

Adding Array Elements

  • push: adds one or more elements to the end of an array.
  • unshift: adds one or more elements to the front of an array.
  • splice: add elements to an array
cars.push("bmw", "maruti");
cars.unshift("ford");
cars.splice(2, 0, "ford", "ferrari");

Removing Array Elements

  • pop: removes the last element from an array and returns that element.
  • shift: removes the first element from an array and returns that element.
  • splice: remove elements from an array
cars.pop();
cars.shift();
cars.splice(2, 3);

Finding elements

By Values

  • indexOf : returns the first index at which a given element can be found in the array, or -1 if it is not present.
  • lastIndexOf: returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.
  • includes: determines whether an array includes a certain value among its entries, returning true or false as appropriate.
numbers = [1, 2, 3, 1, 8, 9];
console.log(numbers.indexOf(1));
console.log(numbers.lastIndexOf(1));
console.log(numbers.indexOf(8) !== -1);
console.log(numbers.includes(8));

By References

  • find: returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
  • findIndex: returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
const courses = [
    {id: 1, name: "html"},
    {id: 2, name: "css"},
    {id: 3, name: "js"},
];
console.log(courses.find(function(course){ return course.name === "html"}));
console.log(courses.findIndex(function(course){ return course.name === "html"}));

Emptying Array

  • There are different ways you can clear an array
// Emptying array
let numbers = [1, 2, 3, 4, 5];

// Solution 1
numbers = [];

// Solution 2
numbers.length = 0;

// Solution 3
numbers.splice(0, numbers.length);

Concat Array

let first = [1, 2, 3];
let last = [4, 5, 6];
let combined = first.concat(last);

Slice

  • slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
  • When called without parameter create a copy of the array.
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(2, 4)); //[3, 4]
console.log(numbers.slice(2)); //[3, 4, 5]
console.log(numbers.slice()); //[1, 2, 3, 4, 5]

Spread Operator

//Concat
let first = [1, 2, 3];
let last = [4, 5, 6];
let combined1  = [...first, ...last];
let combined1  = [...first, 10, ...last, 11];

//Copy
let copy = [...first];

Iterating Array

for-of

let  numbers = [1, 2, 3, 4, 5];
for(let  number  in  numbers)
	console.log(number);

forEach

let  numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index) => console.log(number, index));

Joining

let numbers = [1, 2, 3, 4, 5];
console.log(numbers.join(","));

Sorting

  • By default, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
let countries = ["Srilanka", "India", "China", "Pakistan"];
countries.sort();

Sorting Numbers

  • sort function takes a compare function that defines the sort order
  • If the result is negative (<0), a is sorted before b.
  • If the result is positive (>0), b is sorted before a.
  • If the result is 0, no changes are done with the sort order of the two values.

Sort Number Ascending

let  numbers = [10, 2, 1, 3, 5, 4, 11];
numbers.sort((a, b) =>  a - b);

Sort Number Descending

let  numbers = [10, 2, 1, 3, 5, 4, 11];
numbers.sort((a, b) =>  b - a);

Every

  • Tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
let  numbers = [10, 2, 1, 3, 5, 4, 11];
console.log(numbers.every(n => n > 5));

Some

  • Tests whether at least one element in the array passes the test implemented by the provided function.
let  numbers = [10, 2, 1, 3, 5, 4, 11];
console.log(numbers.some(n => n > 5));

Filter

  • Filter the elements from the given array that pass the test implemented by the provided function.
let  numbers = [10, 2, 1, 3, 5, 4, 11];
console.log(numbers.filter(n => n > 5));

Map

  • Creates a new array populated with the results of calling a provided function on every element in the calling array.
let  numbers = [10, 2, 1, 3, 5, 4, 11];
console.log(numbers.map(n => n * 2));
console.log(numbers.map(n => ({value: n})));

Reduce

  • reduce() method runs a function on each array element to produce (reduce it to) a single value.

With Initial Value

let initialValue = 0;
console.log(numbers.reduce(
    (accumulator, currentValue) => accumulator + currentValue,
    initialValue
));

Without Initial Value

console.log(numbers.reduce(
    (accumulator, currentValue) => accumulator + currentValue
));

Chaining Methods

  • You can chain methods
let  numbers = [10, 2, 1, 3, 5, 4, 11];
let result = numbers.filter(n => n > 5).map(n => ({value: n}));