We work with arrays and their elements on a daily basis as programmers. Being able to quickly look through, filter, sort, and make assertions about elements of an array's elements is critical to our success as developers.
Prototype 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 prototype methods, that allow you to interact with them in certain ways. For example, you might want to add or remove an item from an array. Or inspect the properties on an object. Prototype methods allow you to perform these actions and manipulate your values.
Array Iteration Prototype 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!
In short, instead of using For..loop , we will utilize ES6 array iterating methods.
However, everything could have exceptions in JS. There are occassional times when it makes more sense to use a for loop over something like a forEach. You can read more about why to use one over the other here.
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);
Note: A common mistake is adding ()
after the function: setTimeout(sayHi(), 1000); // wrong
That doesn't work, because 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.
Note: the callback function stays in memory until the scheduler calls it or until clearInterval
is called. So when we don't need the scheduled function anymore, it's better to cancel it.
Note we will be using callback funtions our array methods. Meaning, for every iteration of the method loop, the function in argument will be call back to execute
There are many array prototype methods out there, but we are going to focus on some of these methods:
forEach()
The arr.forEach(cb) method allows to run a function for every element of the array.
// Syntax
arr.forEach(function (item, index, array) {
// ... do something with item
});
// index and array are optional
Example:
["Mango", "Banana", "Orange"].forEach((item, index, array) => {
console.log(`${item} is at index ${index} in ${array}`);
});
The result of the function (if it returns any) is thrown away and ignored.
find()
Imagine we have an array of objects. How do we find an object with the specific condition?
Here the arr.find(cb) method comes in handy.
// Syntax
let result = arr.find(function (item, index, array) {
// if true is returned, item is returned and iteration is stopped
// for falsy scenario returns undefined
});
// index and array are optional
Example:
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.name); // John
In real life arrays of objects is a common thing, so the find()
method is very useful.
The arr.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.
filter()
The find()
method looks for a single (first) element that makes the function return true.
If there may be many, we can use arr.filter(cb).
The syntax is similar to find()
, but filter()
returns an array of all matching elements:
// Syntax
let results = arr.filter(function (item, index, array) {
// if true item is pushed to results and the iteration continues
// returns empty array if nothing found
});
// index and array are optional
Example:
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((item) => item.id < 3);
console.log(someUsers.length); // 2
map()
The arr.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 = arr.map(function (item, index, array) {
// returns the new value instead of item
});
// index and array are optional
Example:
let arr = ["Mango", "Banana", "Orange"];
let lengths = arr.map((item) => item.length);
console.log(lengths); // [5, 6, 6]
sort()
The call to arr.sort() sorts the array in place, changing its element order.
It also returns the sorted array, but the returned value is usually ignored, as arr itself is modified.
Example:
let arr = [1, 2, 15];
// the method reorders the content of arr
arr.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. To sort numerical values, we can do:
arr.sort((a, b) => a - b);
It's quite common to sort a list of objects base on one of the attributes. Example:
let users = [
{ id: 1, name: "John", age: 32 },
{ id: 2, name: "Pete", age: 14 },
{ id: 3, name: "Mary", age: 60 },
];
const compareAge = (userA, userB) => {
if (userA.age > userB.age) return 1;
if (userA.age === userB.age) return 0;
if (userA.age < userB.age) return -1;
};
users.sort(compareAge);
console.log(users);
// [
// { id: 2, name: 'Pete', age: 14 },
// { id: 1, name: 'John', age: 32 },
// { id: 3, name: 'Mary', age: 60 }
// ]
reduce()
The method arr.reduce() is used to calculate a single value based on the array.
// Syntax
let value = arr.reduce(function (accumulator, item, index, array) {
// ...
}, initial);
The function is applied to all array elements one after another and "carries on" its result to the next call.
Arguments:
accumulator
– is the result of the previous function call, equals initial the first time (if initial
is provided).item
– is the current array item.index
– is its position.array
– is the array.Example
let arr = [1, 2, 3, 4, 5];
let result = arr.reduce((sum, current) => sum + current, 0);
console.log(result); // 15
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 arr.reduceRight() does the same, but goes from right to left.
The following methods will help us to work with arrays more easily.
A cheat sheet of array methods:
To add/remove elements:
push(...items)
– adds items to the end,pop()
– extracts an item from the end,shift()
– extracts an item from the beginning,unshift(...items)
– adds items to the beginning.splice(pos, deleteCount, ...items)
– at index pos
deletes deleteCount
elements and inserts items
.slice(start, end)
– creates a new array, copies elements from index start
till end
(not inclusive) into it.concat(...items)
– returns a new array: copies all members of the current one and adds items
to it. If any of items
is an array, then its elements are taken.To search among elements:
indexOf/lastIndexOf(item, pos)
– look for item
starting from position pos
, return the index or -1
if not found.includes(value)
– returns true
if the array has value
, otherwise false
.find/filter(func)
– filter elements through the function, return first/all values that make it return true
.findIndex
is like find
, but returns the index instead of a value.To iterate over elements:
forEach(func)
– calls func
for every element, does not return anything.To transform the array:
map(func)
– creates a new array from results of calling func
for every element.sort(func)
– sorts the array in-place, then returns it.reverse()
– reverses the array in-place, then returns it.split/join
– convert a string to array and back.reduce/reduceRight(func, initial)
– calculate a single value over the array by calling func
for each element and passing an intermediate result between the calls.Additionally:
Array.isArray(arr)
checks arr
for being an array.Note that methods sort
, reverse
and splice
modify the array itself.
Given an array:
const programmers = [
"Dennis Ritchie",
"Brian Kernighan",
"Ken Thompson",
"Linus Torvalds",
"Bjarne Stroustrup",
"Tim Berners-Lee",
"Donald Knuth",
"Alan Turing",
"Mark Zuckerberg",
"Bill Gates",
"Larry Page",
"Elon Musk",
"Jack Dorsey",
"Satoshi Nakamoto",
"Ada Lovelace",
"Grace Hopper",
"Dan Ambramov",
"Jordan Walke",
"Ryan Dahl",
"David Heinemeier Hansson",
"Guido van Rossum",
"Yukihiro Matsumoto",
"Sergey Brin",
"Lyndsey Scott",
"Abhinav Asthana",
"Abhijit Kane",
"Ankit Sobti",
"Loi Tran",
"Charles Lee",
"Tuan Nguyen",
"Tan Vo",
];
Iterator using the for loop
to grab/sequester/fetch/retrieve individual elements in the programmers array:
Use sort()
mutate the programmers array:
Remember, sort() changes the original array.
Use filter()
to define a new variable betterProgrammers
:
Remember, filter() returns a new array where the callback produced a true value using the element.
betterProgrammers
using programmers whose first name starts with L
.const betterProgrammers = ["Loi", "Larry", "Linus"];
betterProgrammers
using programmers whose last name starts with T
.betterProgrammers
using programmers where the first name's length is less than 4 characters.betterProgrammers
using programmers where the first name's length is greater than 4 characters.betterProgrammers
using programmers where the sum of the length of their name's characters is greater than 8.betterProgrammers
using programmers where the sum of the length of their name's characters is less than 8.betterProgrammers
using programmers where the last name begins with the letter K and ends with the letter n.betterProgrammers
using programmers whose first name is exactly 3 characters long.betterProgrammers
using programmers whose first name starts with ‘A'.betterProgrammers
using programmers whose first & last name start with the same character, for example, Abhinav Asthana
.Use map()
to define a new variable betterProgrammers
:
Remember, map() returns a new array where the elements are the return values of the callback passed to map.
betterProgrammers
array of objects with a property fullName
.const betterProgrammers = [
{ fullName: 'Dennis Ritchie' }, { fullName: 'Brian Kernighan' }, ...
]
betterProgrammers
array of objects with a property abbreviation.betterProgrammers
array of objects with a property codeName which is their name's scrambled. For example, 'Loi Tran'
=> 'ioL narT'
, 'Elon Musk'
=> 'nolE ksuM'
betterProgrammers
array of objects with a property birthDate
, which returns a date which places the programmer to be between 18-150 years old.Use reduce()
to define a new variable stew:
stew
which is a string of all first names combined. ("Dennis, Brian, Ken, ...")stew
which is a number, the sum of all first names characters length.stew
which is a number, the sum of all full names characters length.stew
which is a number, the sum of all first names characters length where the first name starts with L.Given
const user = {
currentBalance: 5000,
transactionsMonthToDate: [{}],
};
user.transactionsMonthToDate = [
{
amount: 3000,
type: "deposit",
category: "Salary - Full Time",
},
{ category: "Dining", amount: 50, type: "withdrawal" },
{ category: "Dining", amount: 100, type: "withdrawal" },
{ category: "Rent", amount: 2000, type: "withdrawal" },
{ category: "Groceries", amount: 250, type: "withdrawal" },
{
amount: 250,
type: "withdrawal",
category: "Transportation",
},
{
amount: 250,
type: "withdrawal",
category: "Health",
},
{
amount: 50,
type: "withdrawal",
category: "Travel - Fuel",
},
{ category: "Living", amount: 650, type: "withdrawal" },
{ category: "Groceries", amount: 500, type: "withdrawal" },
{ category: "Living", amount: 250, type: "withdrawal" },
{ category: "Living", amount: 250, type: "withdrawal" },
{
amount: 5000,
type: "deposit",
category: "Salary - Part Time",
},
{ category: "Groceries", amount: 450, type: "withdrawal" },
{
amount: 58,
type: "withdrawal",
category: "Transportation",
},
{
amount: 50,
type: "withdrawal",
category: "Health",
},
{
amount: 100,
type: "withdrawal",
category: "Transportation",
},
{
amount: 150,
type: "withdrawal",
category: "Transportation",
},
{ category: "Groceries", amount: 100, type: "withdrawal" },
{
amount: 100,
type: "withdrawal",
category: "Entertainment",
},
{
amount: 500,
type: "withdrawal",
category: "Entertainment",
},
{ category: "Groceries", amount: 300, type: "withdrawal" },
{
amount: 500,
type: "withdrawal",
category: "Travel - Airline",
},
{
amount: 1500,
type: "withdrawal",
category: "Travel - Hotel",
},
{
amount: 50,
type: "withdrawal",
category: "Travel - Fuel",
},
{ category: "Groceries", amount: 200, type: "withdrawal" },
{
amount: 500,
type: "deposit",
category: "Portfolio Dividends",
},
{
amount: 100,
type: "withdrawal",
category: "Entertainment",
},
{
amount: 100,
type: "withdrawal",
category: "Travel - Fuel",
},
{ category: "Groceries", amount: 200, type: "withdrawal" },
{
amount: 100,
type: "withdrawal",
category: "Entertainment",
},
{
amount: 100,
type: "withdrawal",
category: "Health",
},
];
for loop
to print to the screen the transaction history for the month in this format:Balance: $5000
Transaction History:
- You withdrew $500. The new balance is $4500.
- You deposited $1000. The new balance is $5500.
...
const usdToVND = 23000;
for loop
to print out the transaction history for the month in this format:Balance: ₫100_000,000
Transaction History:
- You withdrew ₫ 1,000,000. The new balance is ₫ 099,000,000.
- You deposited ₫ 10,000,000. The new balance is ₫ 109,000,000.
Given
const order = {
orderItems: [
{ id: "M40", item: "T-shirt", price: 29.9, quantity: 5, gender: 'm', category: 'Summer' },
{ id: "M32", item: "Hoodie", price: 99.9, quantity: 2, gender: 'm', category: 'Winter' },
{ id: "M11", item: "Sandals", price: 19.9, quantity: 1, gender: 'm', category: 'Summer' },
{ id: "M12", item: "Shorts", price: 29.9, quantity: 1, gender: 'm', category: 'Summer' },
{ id: "M13", item: "Exercise Shorts", price: 29.9, quantity: 5, gender: 'm', category: 'Exercise' },
{ id: "M41", item: "Shoes", price: 19.9, quantity: 1, gender: 'm', category: 'Summer' },
{ id: "M49", item: "Socks", price: 5.9, quantity: 10, gender: 'm', category: 'Undergarment' },
{ id: "M01", item: "Belt", price: 15.9, quantity: 1, gender: 'm', category: 'Accessory' },
{ id: "M42", item: "Underwear", price: 19.9, quantity: 10, gender: 'm', category: 'Undergarment' },
{ id: "F71", item: "T-shirt", price: 39.9, quantity: 5, gender: 'f', category: 'Summer' },
{ id: "F81", item: "Dress", price: 49.9, quantity: 5, gender: 'f', category: 'Summer' },
{ id: "F91", item: "Skirt", price: 39.9, quantity: 5, gender: 'f', category: 'Summer' },
{ id: "F01", item: "Shoes", price: 19.9, quantity: 10, gender: 'f', category: 'Summer' },
{ id: "F32", item: "Hoodie", price: 99.9, quantity: 2, gender: 'f', category: 'Winter' },
{ id: "F34", item: "Sandals", price: 19.9, quantity: 2, gender: 'f', category: 'Summer' },
{ id: "F36", item: "Shorts", price: 39.9, quantity: 3, gender: 'f', category: 'Summer' },
{ id: "F12", item: "Exercise Shorts", price: 29.9, quantity: 5, gender: 'f', category: 'Exercise' },
{ id: "F19", item: "Sleeping", price: 39.9, quantity: 3, gender: 'f', category: 'Undergarment' },
{ id: "F42", item: "Socks", price: 5.9, quantity: 10, gender: 'f', category: 'Undergarment' },
{ id: "F43", item: "Underwear", price: 39.9, quantity: 10, gender: 'f', category: 'Undergarment' },
{ id: "F44", item: "Bra", price: 29.9, quantity: 10, gender: 'f', category: 'Undergarment' },
{ id: "F01", item: "Belt", price: 15.9, quantity: 1, gender: 'f', category: 'Accessory' },
];
}
originalDate
property as the current date.delivered
property as false.subtotal
property, the sum of all the items in the order.salesTax
property calculated at .07
percent * subtotal.grandTotal
property, the sum of all the items in the order & sales tax.If you've completed these exercises then good work. Practice makes perfect , or build confidence at least. So if you want to improve your codding skills try
clonning this repo and continue working inside the js
folder.