DEV Community

Cover image for Javascript array methods to master
ALAMIN JUMA MAGOTI
ALAMIN JUMA MAGOTI

Posted on

6

Javascript array methods to master

An array is a type of data structure that stores items that can be accessed at an index.
For instance here is an empty array:
[]
and here is an array element containing different kinds of data:
[1, "Alamin", true, {name: 'alamin', age: 25}].

Arrays contain three kinds of methods, the mutator methods that modify the original array, accessor methods that returns a new value and iterable methods which accesses each array item at a time.

Here, I will focus mostly on the common array iterable methods like map(), filter(), find(), every(), some(), forEach(), reduce().

1: map() array method
A map() methods return a new array copy of the original array which can then be used to access each array element and return its value for each iteration.

let arr = [1,2,3,4,5];
let arrayMap = arr.map(item => item += item)
console.log(arrayMap);
//[ 2, 4, 6, 8, 10 ]

Enter fullscreen mode Exit fullscreen mode

This code maps arr to arrayMap using a map() method and enables it to access each item , where a value is return containing an item added by itself.
Lets say the Government increases the taxes on food items by 20 shillings, but we still need to know the previous prices.

const initialFoodPrices = [
    { image: "🍕", name: "pizza", price: 1000 },
    { image: "🍔", name: "burger", price: 800 },
    { image: "🥪", name: "sandwich", price: 600 },
   ] 
Enter fullscreen mode Exit fullscreen mode

if we map into initialFoodPrices, *item * returns an array of objects
initialFoodPrices.map(item => item)
js image
we can access an element of each object using a .dot notation on since item returns an objects data, for example

initialFoodPrices.map(item => item.price)
//[1000, 800, 600]
will return all prices in the objects into a new array. We can then add the added taxes to the prices to return the new prices

initialFoodPrices.map(item => item.price + 20)
(3) [1020, 820, 620]

**Note if you don't return your value on a map(), your values will be undefined. *

2: forEach() array method
Array forEach() is used when one needs to iterate over array items one-by-one so that you can do something with them. The difference between map() and forEach(), is that map() returns a new array
while forEach(), does not return any value.
For example the code below, we are iterating through runners arrays and accessing every athlete to show if they run 100 meters race:

let runners = ['Kipchoge', 'Kipchumba', 'Koskei']
.forEach((athlete) => {
  console.log(`${athlete} runs 100 meters`)
})
//Kipchoge runs 100 meters
//Kipchumba runs 100 meters
//Koskei runs 100 meters
Enter fullscreen mode Exit fullscreen mode

forEach() is useful when populating data on the DOM or target an event to a group of HTML elements. Below shows how one can add an eventListner to a group of buttons with the same class/id name.

<div class="jumbotron">
  <button class=" btn-primary text-center btns">Go blue</button>  
  <button class=" btn-white text-center btns">Go white</button>
  <button class=" btn-danger text-center btns">Go red</button>
</div>
Enter fullscreen mode Exit fullscreen mode

buttons with same class
To add an event listner to the three buttons, we will use querySelectorAll('.btns') which returns a nodeList containing all the button elements.
const buttons = document.querySelectorAll('.btns')

nodeList of buttons

if you eventListner directly to the grabbed elements on buttons, it will give you an error of buttons.addEventListner is not a function.
buttons.addEventListener('click', () => {document.body.style.backgroundColor = "#fff000"})

typeError
This is because we are trying to access the nodeList as one element, yet it is an array of elements(i.e the buttons).
The nodeList exposes methods like forEach() which can help you access each button element in the nodeList and add an eventListner to each button. Lets remove the error using forEach()


    buttons.forEach(button => 
                    button.addEventListener
                    ('click', function goYellow() {

         console.log('I laugh for every click 😀😀😀😀😀😀😀')
    }))
Enter fullscreen mode Exit fullscreen mode

when every button is click, an event lister of click is added to every button element in the nodeList, and a function call is executed.

click

3: filter() array method
filter() **returns **a new array containing only the items you specified.
for example, you may need to filter only items that are above 450 , since they are expensive from a menu list

const availableFoods = [
    {id: "qwe234dfh", name: "Burger", image:"🍔🍔", price: 234},
    {id: "qwe2356dxh", name: "pizza", image:"🍕🍕", price: 400},
    {id: "qwe2456yh", name: "meat", image:"🍖🍖", price: 500},
    {id: "qwe2785yh", name: "chicken", image:"🍗🍗", price: 1200},
]
const expensiveItems = availableFoods.filter((items) => {return items.price > 450})
console.log(expensiveItems)

//result
// {id: "qwe2456yh", name: "meat", image:"🍖🍖", price: 500},
// {id: "qwe2785yh", name: "chicken", image:"🍗🍗", price: 1200},
Enter fullscreen mode Exit fullscreen mode

Array reduce
Array reduced is used when one needs a single value, mostly when one needs to end up with a calculated value of the whole array. it has a *prev **and **next *, where prev refers to the value returned on the next iteration, and next as the current value.

 const reducedValues = [1, 2, 3, 4, 5].reduce((prev, next) => {
    console.log(`prev: ${prev}, next: ${next}`)
    return prev + next
})
Enter fullscreen mode Exit fullscreen mode

reduced
Lets say we have a list of food menu and we need to calculate the total price

//lets calculate the tottal price of this dinner
let mydinner = [
    { id: "qwe234dfh", name: "Burger", image: "🍔🍔", price: 500 },
    { id: "qwe2456yh", name: "meat", image: "🍖🍖", price: 600 },
    { id: "qwe2785yh", name: "chicken", image: "🍗🍗", price: 400 },
]
Enter fullscreen mode Exit fullscreen mode

For this, we need to access the prices inside an object hence we will first need to return an array containing all prices, then reduce the returned array.
We will map into the array of objects and access the objects.prices values into an new array
const totalP = mydinner.map(foodPrice => foodPrice.price)

mapped
After that, we can then reduce the price values into a single value, totalPrice

const totalP = mydinner.map(foodPrice => foodPrice.price)
                       .reduce((prev, next) => {
                                return prev + next
                                                    }, 0);
                        console.log("total bill is ..... ", totalP, "ksh")
Enter fullscreen mode Exit fullscreen mode

reduce

some() array method
some() checks if an array item passes a particular test, hence
returning a boolean (true or false). For example, we can use some() to check if a certain group of students are software developers.

let students = [
  {name: 'John', email: 'john@gmail.com', softwareDev: "true"},
  {name: 'John', email: 'john@gmail.com', softwareDev: "false"},
  {name: 'John', email: 'john@gmail.com', softwareDev: "true"},
]
.some((item) => {return item.softwareDev})
console.log(students)
//true 
Enter fullscreen mode Exit fullscreen mode

returns true because yes some persons in the array are a softwareDev

..................................................................
Alamin Juma
Enjoys hiking and swimming

Top comments (1)

Collapse
 
japhhans profile image
Sesugh Ahangba

I am a beginner