Map, ForEach, Filter, Find, Reduce, FindIndex in Javascript

Rudomaru
3 min readDec 3, 2020

When it comes to working with an array in javascript these methods are the backbone of everything. Today I am going to implement these methods on an array of string and array of objects.

What are these methods anyway?

Map() method that allows to loop through an array and creates a new array with the results of calling a function for every array element

ForEach() method calls a function once for each element in an array, in order. Note: the function is not executed for array elements without values.

Filter() method creates an array filled with all array elements that pass a test (provided as a function).

Find() method returns the value of the first element in an array that passes a test (provided as a function). If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values) otherwise it returns undefined

Reduce() method reduces the array to a single value. It executes a provided function for each value of the array (from left-to-right). The return value of the function is stored in an accumulator (result/total).

FindIndex() method returns the index of the first element in an array that passes a test (provided as a function). If it finds an array element where the function returns a true value, find index() returns the index of that array element (and does not check the remaining values) otherwise it returns -1

Let's jump into Examples:

Let me define the arrays we are going to use

const names = [‘Rudo Mapfumba’, ‘James Patrics’, 'Melody Chamz', 'Belinda Greens', 'Faith Kings'];const birthdays = ['20/01/1981', '17/09/1995', '04/7/1992', '19/10/1998', '25/01/1998'];const occupations = ['accountant', 'finance manager', 'programmer', 'assistance', 'programmer'];const salaries = [2500, 3100, 1900, 3900, 4200];

Task1:Apply the Map() method

//display names to the screen
names.map(name => return (<li>{name}</li>))

Task2: Appy the forEach() method

//add 100 to each salary
const newSalaries = salaries.forEach(salary => {
return salary + 100;
})
console.log(newSalaries)

Task3: Apply the filter() method.

//return where birth year is 1998
const results = birthdays.filter(date => {
let dateObject = new Date(date);
return dateObject.getFullYear() === 1998
});
//return number of occupations which are programmers
const num = occupations.filter(e => e === "programmer").length

Task 4: Apply the Reduce method.

//return the today number of salary
const total = salaries.reduce((acc, value) => {
return acc += value;
})

Task 5: Apply the find() method.

//return name with surname “Kings”
const name = names.find(name => name.includes("Kings"));
//find salary =2100;
const getSalary = salaries.find(salary => salary === 2100);

Task 6: Apply the findIndex() method.

//find index of “James Patrics” 
const index = names.findIndex('James Patrics')

I guess now we all have an idea of how these functions work so I thought of taking it deeper by applying these methods on a buying cart in an application

  1. Add item to cart
  2. Remove item to cart
  3. Empty cart
  4. Find an item in the cart
  5. Get total in the cart
the cart output

Below is the starter HTML file:

  1. Display Cart items

2. Add Item to cart

we are going to use unshift to add an element at the first position in the array

3. Delete from cart

we are going to add an event listener to the delete button and remove the item from the cart array by id using filter

//handle deleteremoveButton.addEventListener(“click”, () => {console.log(“clicked”)carts = carts.filter(cart => cart.id !== e.id);console.log(carts)render();})

4. Calculate the total

we are going to use the reduce method to calculate the total amount of elements in the cart

totalAmount = carts.reduce((acc, item) => {  return acc.price += item.price})

5. Search in Cart

//searchconst handleSearch = (e) => {
e.preventDefault();
const searchQuery = document.querySelector(‘[name = “search”]’);
if(searchQuery.value !== “”){
let query = searchQuery.value.toLowerCase()
carts = carts.filter(cart =>
cart.title.toLowerCase().includes(query)
);
render()
}
}
searchForm.addEventListener(“submit”, handleSearch)

6. Empty Cart

const handleDeleteCart = () => {carts = [];render();}deleteCart.addEventListener(“click”, handleDeleteCart)

full Github repository here: https://github.com/maru25-alt/myCart.git

till next Time Happy Coding!!!

--

--