Array

We have learned about array in the previous lesson. Can you once tell in your word what is an array in Javascript again?

Methods

Methods are functions that allow you to manipulate the value of a particular data type or class.

JavaScript comes with several built-in data types(*) that each have their own methods, that allow you to interact with them in certain ways.

Methods allow you to perform these actions below and manipulate your values.

For example:

For example, methods of

Array methods

There are many array methods. In this lesson, we will go through some important methods below:

Array Iteration Methods

Loop through an existing array and apply a callback function to each element that might mutate each element and return a new value.

WAIT. Can't we already iterate through arrays with a for loop?! Yes, we can often accomplish the same thing using a for loop, but the array iteration methods do provide some good benefits!

There are occasional times when it makes more sense to use a for loop over something like a forEach. We'll discuss more about this later.

We'll focus on these methods:

Others methods

(*) Build-in data types:

Before jump into the array methods, let's talk about Callback function - a type of function that we mostly use in every array methods.

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

An example of callback functions is the Event Listener function that you pass in the addEventListener() function.

Another example is in setTimeout() and setInterval():

function sayHi(name) {
  console.log(`Hi ${name}`);
}

// This calls sayHi() after one second
setTimeout(sayHi, 1000, "CoderSchool");
let n = 1;
function counter() {
  console.log(n);
  n = n + 1;
}

// repeat with the interval of one second
let timerId = setInterval(counter, 1000);
// stop after 5 seconds
setTimeout(() => {
  clearInterval(timerId);
}, 5000);

Note:

Array iteration methods perform some operation on each element of array.

forEach()

The array.forEach(callbackFunction) method allows to run a function for every element of the array. The provided function is user defined, it can perform any kind of operation on array.

Syntax:

array.forEach((item, index, array) => {
  // ... do something with item
});
// index and array are optional

Example:

const fruit = ["Mango", "Banana", "Orange"];
fruit.forEach((element) => {
  console.log(element);
});

Result:

Mango;
Banana;
Orange;

Parameters:

const fruit = ["Mango", "Banana", "Orange"];
fruit.forEach((element, index, array) => {
  console.log(`${element} is at index ${index} in ${array}`);
  console.log(array);
});

Result:

Mango is at index 0 in Mango,Banana,Orange
[ 'Mango', 'Banana', 'Orange' ]
Banana is at index 1 in Mango,Banana,Orange
[ 'Mango', 'Banana', 'Orange' ]
Orange is at index 2 in Mango,Banana,Orange
[ 'Mango', 'Banana', 'Orange' ]

Return value:

undefined! The result of the function (if it returns any) is thrown away and ignored.

Converting a for loop to forEach:

We can often achieve the same result with forEach by using for loop. But there some benefit over it. It can be say that forEach is easier to read with a lower chance of accidental errors.

Example:

const fruits = ["Mango", "Banana", "Orange"];
const copyFruits = [];

// before
for (let i = 0; i < fruits.length; i++) {
  copyFruits.push(fruits[i]);
}

// after
fruits.forEach((fruit) => {
  copyFruits.push(fruit);
});

The example above seems the same in both cases. Let's check another one.

const foodArray = [
  { name: "Broken rice", ingredients: ["rice", "pork", "tomato"] },
  { name: "Pho", ingredients: ["noodle", "beef", "broth"] },
  {
    name: "Crispy Vietnamese Crêpes",
    ingredients: ["rice flour", "shrimp", "coconut cream"],
  },
];

for (let i = 0; i < foodArray.length; i++) {
  let food = foodArray[i];
  console.log(food.name);
  for (let j = 0; j < food.ingredients.length; j++) {
    let ingredient = food.ingredients[j];
    console.log(ingredient);
  }
}

Result:

Broken rice //name
rice
pork
tomato
Pho //name
noodle
beef
broth
Crispy Vietnamese Crêpes //name
rice flour
shrimp
coconut cream

Having those two i and j variable add a lot confusion to your code. Here is the result using forEach instead:

const foodArray = [
  { name: "Broken rice", ingredients: ["rice", "pork", "tomato"] },
  { name: "Pho", ingredients: ["noodle", "beef", "broth"] },
  {
    name: "Crispy Vietnamese Crêpes",
    ingredients: ["rice flour", "shrimp", "coconut cream"],
  },
];

foodArray.forEach((food) => {
  console.log(food.name);
  food.ingredients.forEach((ingredient) => {
    console.log(ingredient);
  });
});

Read more about other reason why we use one over other here.

find()

Imagine we have an array of objects. How do we find an object with the specific condition?

Here the array.find(cb) method comes in handy.

Syntax

let result = array.find(function (item, index, array) {
  // if true is returned, item is returned and iteration is stopped
  // for falsy scenario returns undefined
});

Example: find an object user in the users array that has the id equal to 1

let users = [
  { id: 1, name: "John" },
  { id: 2, name: "Pete" },
  { id: 3, name: "Mary" },
];

let user = users.find((item) => item.id == 1);

console.log(user); // { id: 1, name: "John" }

Parameters:

Return value:

In real life arrays of objects is a common thing, so the find() method is very useful.

The array.findIndex() method is essentially the same, but it returns the index where the element was found instead of the element itself and -1 is returned when nothing is found.

—give more example to emphasize the case that return only first element

filter()

The find() method looks for a single (first) element that makes the function return true.

If there may be many, we can use array.filter(cb).

The syntax is similar to find(), but filter() returns an array of all matching elements:

Syntax

let results = array.filter(function (element, index, array) {
  // if true element is pushed to results and the iteration continues
  // returns empty array if nothing found
});

Example: find all the object users that has the id lower than 3

let users = [
  { id: 1, name: "John" },
  { id: 2, name: "Pete" },
  { id: 3, name: "Mary" },
];

// returns array of the first two users
let someUsers = users.filter((element) => element.id < 3);

console.log(someUsers);

—- result image, running a test case for explanation

Result:

[
  { id: 1, name: "John" },
  { id: 2, name: "Pete" },
];

Parameters:

Return value:

map()

The array.map(cb) method is one of the most useful and often used.

It calls the function for each element of the array and returns the array of results.

Syntax

let result = array.map(function (element, index, array) {
  // returns the new value instead of element
});

Example:

let array = ["Mango", "Banana", "Orange"];
let lengths = array.map((element) => element.length);
console.log(lengths); // [5, 6, 6]

Parameters:

Return value:

reduce()

The method array.reduce(cb) is used to calculate a single value based on the array.

Syntax

let value = array.reduce((accumulator, element, index, array) => {
  // ...
}, initialValue);

The function is applied to all array elements one after another and "carries on" its result to the next call.

Example: without initialValue

let arr = [1, 2, 3, 4, 5];

let result = array.reduce((sum, current) => sum + current);

console.log(result); // 15

This callback Function invoke 4 times because there is no initialValue.

Therefore the accumulator is initialized to the first value in the array. comparison array methods

Example: with initialValue

let arr = [1, 2, 3, 4, 5];

let result = array.reduce((sum, current) => sum + current, 5);

console.log(result); // 15

This callback Function invoke 4 times because there is initialValue. Therefore the element initialized to the first value in the array comparison array methods

Parameters:

Return value:

The value results from running the callbackFunction through entire array.

Another example: sum of value in an object array

let cart = [
  { id: 1, name: "Banana", price: 0.5, quantity: 5 },
  { id: 2, name: "Mango", price: 1.5, quantity: 3 },
  { id: 3, name: "Orange", price: 0.9, quantity: 7 },
];

let totalPrice = cart.reduce(
  (total, item) => total + item.price * item.quantity,
  0
);
console.log(totalPrice); // $13.3

The method array.reduceRight() does the same, but goes from right to left.

sort()

The call to array.sort(compareFunction) sorts the array in place, changing its element order.

It also returns the sorted array, but the returned value is usually ignored, as array itself is modified.

Syntax:

array.sort(compareFunction(a, b)); // return a sorted array
//compareFunction is optional

Without compareFunction

Example:

let arr = [1, 2, 15];

// the method reorders the content of array
array.sort();

console.log(arr); // 1, 15, 2

The order became 1, 15, 2, because the items are sorted as strings by default. For string "2" > "15" indeed.

With compareFunction

CompareFunction take two arguments: firstElement and secondElement for comparison. The value return from the compareFunction decides the order of elements in the array. The compare function should return a negative, zero, or positive value

comparison array methods

Parameters:

Return value:

reverse()

A method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

Syntax:

array.reverse();

Example:

const fruits = ["Mango", "Orange", "Avocado", "Lemon", "Lychee"];

const fruitCount = fruits.reverse();

console.log(fruitCount); // [ 'Lychee', 'Lemon', 'Avocado', 'Orange', 'Mango' ]
console.log(fruits); // [ 'Lychee', 'Lemon', 'Avocado', 'Orange', 'Mango' ]

Return value:

comparison array methods

toString()

A method convert array to string.

Syntax:

array.toString();

Example:

const fruits = ["Mango", "Orange", "Apple"];
const fruitString = fruits.toString();
console.log(fruitString); //Mango,Orange,Apple

Return value:

join()

Also a method "join" array to string, but this time, you can specify the separator

Syntax:

array.join();

Example:

const fruits = ["Mango", "Orange", "Apple"];
const fruitString = fruits.join("-");
console.log(fruitString); //Mango-Orange-Apple

Return value:

Transform the array:

push()

A method that adds one or more elements to the end of an array and return a length of the array

Syntax:

array.push(element1, element2,..., elementN)

Example:

const fruits = ["Mango", "Orange"];

const fruitCount = fruits.push("Avocado");

console.log(fruitCount); // 3
console.log(fruits); // [ 'Mango', 'Orange', 'Avocado' ]

fruits.push("Lemon", "Lychee");

console.log(fruits); //[ 'Mango', 'Orange', 'Avocado', 'Lemon', 'Lychee' ]

Parameters

Return value:

unshift()

unshift() is a method just like push() but instead of adding an element to the end of an array, unshift() add an element to the beginning of an array. Read more about shift here

pop()

A method that removes the last element from an array and returns that element

Syntax:

array.push(element1, element2,..., elementN)

Example:

const fruits = ["Mango", "Orange", "Avocado", "Lemon"];

const removeFruit = fruits.pop();

console.log(removeFruit); // Lemon
console.log(fruits); // [ 'Mango', 'Orange', 'Avocado' ]

Return value:

shift()

shift() is a method just like pop() but instead of removing the last element from an array, shift() remove the first element. Read more about shift here

slice()

Syntax:

array.slice(startIndex, endIndex);

Example:

const fruits = ["Mango", "Orange", "Avocado", "Lemon"];

const sliceFruit1 = fruits.slice(2);
console.log(sliceFruit1); //[ 'Avocado', 'Lemon' ]

const sliceFruit2 = fruits.slice(1, 3);
console.log(sliceFruit2); //[ 'Orange', 'Avocado' ]

const sliceFruit3 = fruits.slice(-3);
console.log(sliceFruit3); //[ 'Orange', 'Avocado', 'Lemon' ]

const sliceFruit4 = fruits.slice(2, -1);
console.log(sliceFruit4); //[ 'Avocado' ]

Parameters:

Return value:

splice()

A method modify the contents of an array by

Syntax:

array.splice(startIndex, deleteCount, item1, item2,...,itemN)

Example:

const fruits = ["Mango", "Orange", "Avocado", "Lemon"];

const spliceFruit1 = fruits.splice(1, 0, "Apple"); //insert at index 1
console.log(spliceFruit1); //[ ]
console.log(fruits); //[ 'Mango', 'Apple', 'Orange', 'Avocado', 'Lemon' ]

const spliceFruit2 = fruits.splice(3, 2, "Lychee"); //remove 2 elements from index 2 and add Lychee to index 3
console.log(spliceFruit2); //[ 'Orange', 'Avocado' ]
console.log(fruits); // [ 'Mango', 'Apple', 'Lychee', 'Lemon' ]

Parameters:

Return value:

concat()

A method use to merge two or more arrays and return a new array

Syntax:

array.concat(value1,..., valueN) // valueN can be arrays or values

Example:

const fruit1 = ["Mango", "Orange"];
const fruit2 = ["Strawberry", "Coconut", "Lemon"];
const fruit3 = ["Kiwi"];

const mergeFruit = fruit1.concat(fruit2);
console.log(mergeFruit); //[ 'Mango', 'Orange', 'Strawberry', 'Coconut', 'Lemon' ]

const mergeFruit2 = fruit1.concat(fruit2, fruit3);
console.log(mergeFruit2); //[ 'Mango', 'Orange', 'Strawberry', 'Coconut', 'Lemon', 'Kiwi' ]

const addSingleFruit = mergeFruit.concat("Kiwi");
console.log(addSingleFruit); //[ 'Mango', 'Orange', 'Strawberry', 'Coconut', 'Lemon', 'Kiwi' ]

Parameters:

Return value:

Convert string to array:

split()

Syntax:

string.split(separator, limit);

Example:

const randomString = "Hello World! A new day has come.";

//a space " " is the pattern
const stringArray = randomString.split(" ");
console.log(stringArray); //[ 'Hello', 'World!', 'A', 'new', 'day', 'has', 'come.' ]

const randomString2 = "Hello-World! A-new-day-has-come.";
//"-" is now the pattern that split looking for
const stringArray2 = randomString2.split("-");
console.log(stringArray2); //[ 'Hello', 'World! A', 'new', 'day', 'has', 'come.' ]

const stringArray3 = randomString.split("");
console.log(stringArray3)[
  ("H",
  "e",
  "l",
  "l",
  "o",
  " ",
  "W",
  "o",
  "r",
  "l",
  "d",
  "!",
  " ",
  "A",
  " ",
  "n",
  "e",
  "w",
  " ",
  "d",
  "a",
  "y",
  " ",
  "h",
  "a",
  "s",
  " ",
  "c",
  "o",
  "m",
  "e",
  ".")
];

const stringArray4 = randomString.split("", 3);
console.log(stringArray4)[("H", "e", "l")];

Parameters:

Return value:

Spread syntax

This spread syntax allows an iterable such as an array expression or string to be expanded in places. We'll learn more about this later. Read more here Example:

const randomString = "Hello World! A new day has come.";
const stringArray = [...randomString]; //[ 'H','e','l','l','o',' ','W','o','r','l','d','!',' ','A',' ','n','e','w',' ','d','a','y',' ','h','a','s',' ','c','o','m','e','.' ]

Convert string to array:

There are 3 methods we can use here

Object.keys()

A method returns an array of all keys in the object Example:

const user = {
  firstName: "Jon",
  lastName: "Snow",
  email: "jonstark@gmail.com",
};

const userKey = Object.keys(user);
console.log(userKey); // [ 'firstName', 'lastName', 'email' ]

Object.values()

A method returns an array of all values in the object Example:

const user = {
  firstName: "Jon",
  lastName: "Snow",
  email: "jonstark@gmail.com",
};

const userValue = Object.values(user);
console.log(userValue); // [ 'Jon', 'Snow', 'jonstark@gmail.com' ]

Object.entries()

A method returns an array of [key, value] pairs from the given object Example:

const user = {
  firstName: "Jon",
  lastName: "Snow",
  email: "jonstark@gmail.com",
};

const userValue = Object.entries(user);
console.log(userValue);

Result:

[
  ["firstName", "Jon"],
  ["lastName", "Snow"],
  ["email", "jonstark@gmail.com"],
];

array-method-cheatsheet-all