We have learned about array in the previous lesson. Can you once tell in your word what is an array in Javascript again?
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
There are many array methods. In this lesson, we will go through some important methods below:
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:
forEach(cb)
- Calls the callback function for every element, does not return anything.find(cb)
- Filter elements through the function, return first values that make the function return true.filter(cb)
- Filter elements through the function, return all values that make the function return true.map(cb)
- Creates a new array from results of calling func for every element.reduce(cb, initialValue)
- Calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.push()
– Insert an element at the end of the array.unshift()
– Insert an element at the beginning of the array.pop()
– Remove an element from the end of the array.shift()
– Remove an element from the beginning of the array.slice()
– Create a shallow copy of an array.splice()
– Add, update, and remove elements in an array.concat()
- Merges one or more arrays and returns a merged array.sort()
- Sorts the array in-place, then returns it.reverse()
- Reverses the array in-place, then returns it.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()
:
setTimeout(callback, delay, arg1, arg2, ...)
allows us to run a function once after the interval of time.setInterval(callback, delay, arg1, arg2, ...)
allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.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);
()
after the function: setTimeout(sayHi(), 1000); // wrong
setTimeout
expects a reference to a function. And here sayHi()
runs the function, and the result of its execution is passed to setTimeout
. In our case the result of sayHi()
is undefined
(the function returns nothing), so nothing is scheduled.clearInterval
is called. So when we don't need the scheduled function anymore, it's better to cancel it.Array iteration methods perform some operation on each element of array.
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.
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;
callbackFunction
: Function to execute on each element. It accepts between one and three arguments: element
: The current element being processed in the arrayindex
(optional): The index of element
in the arrayarray
(optional): The array forEach()
was called uponconst 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' ]
undefined
! The result of the function (if it returns any) is thrown away and ignored.
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.
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.
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" }
callbackFunction
: Function to execute on each element. It accepts between one and three arguments: element
: The current element being processed in the arrayindex
(optional): The index of element
in the arrayarray
(optional): The array forEach()
was called uponcallbackFunction
return true, the find()
method will returns the value of first element in the provided array that match with the provided functioncallbackFunction
return false, undefined
is returnedIn 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
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:
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" },
];
callbackFunction
: Function to execute on each element. It accepts between one and three arguments: element
: The current element being processed in the arrayindex
(optional): The index of element
in the arrayarray
(optional): The array forEach()
was called uponcallbackFunction
return true, the element is pushed to that new array and the iteration continues till the end of the filtered arraycallbackFunction
return false, empty array is returnedThe 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.
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]
callbackFunction
: Function to execute on each element. It accepts between one and three arguments: element
: The current element being processed in the arrayindex
(optional): The index of element
in the arrayarray
(optional): The array map()
was called uponcallbackFunction
The method array.reduce(cb) is used to calculate a single value based on the array.
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.
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
callbackFunction
: Function to execute on each element. It accepts between one and four arguments: accumulator
: is the result of the previous function call, equals initialValue
the first time (if initialValue
is provided).element
: The current element being processed in the arrayindex
(optional): The index of element
in the arrayarray
(optional): The array map()
was called uponinitialValue
(optional): A value to which accumulator is initialized the first time the callback is called. initialValue
is specified, that also causes element
to be initialized to the first value in the array.initialValue
is not specified, accumulator is initialized to the first value in the array, and element
is initialized to the second value in the array.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.
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.
array.sort(compareFunction(a, b)); // return a sorted array
//compareFunction is optional
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.
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
let users = [
{ id: 1, name: "John", age: 32 },
{ id: 2, name: "Pete", age: 14 },
{ id: 3, name: "Mary", age: 60 },
];
users.sort((userA, userB) => {
if (userA.age > userB.age) {
return 1; // sort userB before userA
}
if (userA.age === userB.age) {
return 0; // keep original order of userA and userB
}
if (userA.age < userB.age) {
return -1; // sort userA before userB
}
});
console.log(users);
Result:[
{ id: 2, name: "Pete", age: 14 },
{ id: 1, name: "John", age: 32 },
{ id: 3, name: "Mary", age: 60 },
];
array.sort((a, b) => a - b);
Example:const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => {
return a - b;
});
console.log(numbers); //[1, 2, 3, 4, 5]
numbers.sort((a, b) => {
return b - a;
});
console.log(numbers); //[5, 4, 3, 2, 1]
compareFunction
(Optional): compareFunction
: firstElement
: the first element for comparisonsecondElement
: the second element for comparisonA method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.
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' ]
A method convert array to string.
array.toString();
Example:
const fruits = ["Mango", "Orange", "Apple"];
const fruitString = fruits.toString();
console.log(fruitString); //Mango,Orange,Apple
arrayl.length === 0
, return empty stringAlso a method "join" array to string, but this time, you can specify the separator
array.join();
Example:
const fruits = ["Mango", "Orange", "Apple"];
const fruitString = fruits.join("-");
console.log(fruitString); //Mango-Orange-Apple
arrayl.length === 0
, return empty stringTransform the array:
A method that adds one or more elements to the end of an array and return a length of the array
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' ]
elementN
: the element(s) to add to the end of arraylength
property of the array upon with the method was calledunshift()
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
A method that removes the last element from an array and returns that element
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' ]
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
startIndex
to endIndex
(end not included).startIndex
and endIndex
represent the index of items in that array.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' ]
A method modify the contents of an array by
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' ]
startIndex
: index at which to start extractiondeleteCount
(optional): number of elements to remove from startIndex
item1, item2,...,itemN
(optional): the elements to add, start from startIndex
. If there is no item, splice()
will only removeA method use to merge two or more arrays and return a new array
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' ]
valueN
: can be arrays or valuestring.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")];
separator
: The pattern describing where each split should occur. The separator can be a simple string or it can be a regular expression.limit
(optional): A non-negative integer specifying a limit on the number of substrings to be included in the arrayThis 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','.' ]
There are 3 methods we can use here
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' ]
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' ]
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"],
];