A Beginners Guide to Javascript Array Methods

A Beginners Guide to Javascript Array Methods

As a Javascript developer understanding how to work with Arrays and different array methods will save you from wasting a lot of time.

This article is concerned with giving you a basic understanding of how the most important and commonly used array methods are used when working with arrays. The goal is that after digesting this article, you're able to explain what these array methods do off the top of your head and as well as use this basic concept to work on more complex problems.

ForEach()

It is very common to work with arrays in javascript and most often than not, we tend to have to need to loop through arrays. They're already common ways to loop over arrays such as using the: for loop and the for...of the loop. But what makes the forEach() better?

I think that the forEach method is easier on the eyes and it makes it better to understand your code or if you ever come across someone else's code.

An important point to note with using forEach() is that it doesn't return any value, if it did, it would be undefined. So how does this work:

The forEach() method accepts two parameters: ' The callback Function' and ' visarga We'd focus more on the callback function, cause its most commonly used. The callback function accepts three parameters, the current value of the array, the index of that current value, and the entire array.

forEach(callbackFn(value,index,array){
}thisarg)
/*Most often we find ourselves only concerned with  each 
of individual array values and we ignore the index and array*/

The forEach() picks each value in the array and invokes a function on it until it reaches the end of the array.

const numbers = [3,4,5,2,1]
/*using the old for..loop, i represents each element in the array of numbers*/
for(let i = 0; i < numbers.length ; i++){
    let b = numbers[i] * 2
    console.log(b)
}

/* num represents each element in the array of numbers, each element
is multiplied by two,and the answers all stored in the variable a*/
 numbers.forEach((num)=>{
   let a = num * 2
    console.log(a)/* 6 ,8,10,3,2*/
})

With the code snippet above, I compared the for loop and the forEach () method, to achieve the same result. I don't know about you but the forEach() seems easier to use and understand.

map()

Map()method is another very useful method when it comes to arrays. Three things to note when it comes to the map():

  • Use it when you want to modify or transform values in an array.

  • Works just like a forEach(), but it doesn't give 'undefined when a return value is specified.

  • Map() always returns a new array

Like I said earlier Map() works just like the forEach(), the main difference here is that it returns the results in a new array. If you do not pass a return value, the map() method you used will throw back 'undefined'.

Map() accepts two arguments: a callback Function and thisarg. The callback function accepts three arguments(value,index,array).Our main concern is the value because that is what you will most likely use every time.

const proLang = ['javascript','css','html','react','vue','angular']
let easyproLang = proLang.map((lang)=>{
   let a = `${lang} is very easy to comprehend`
   return a;
})
console.log(easy Roland)/*
[
  'javascript is very easy to comprehend',
  'CSS is very easy to comprehend',
  'HTML is very easy to comprehend',
  'react is very easy to comprehend',
  'vue is very easy to comprehend',
  'angular is very easy to comprehend'
]
*/

Like in the example above, I created a new variable called easyproLang(easy programming language), which would store easy to comprehend languages. So using the map() method, it took in a callback fn with the parameter called 'lang'. 'lang' represents each of the values inside the proLang array(javascript, CSS, HTML, react,vue, and angular). The callbackFn works on each of the values and replaces them at each point in the sentence.

sort()

Sort() is a method that helps you to rearrange your array, whether it's in ascending order or descending order. You can sort your array in two ways, depending on what you want to sort.

  • Method 1: This method involves using sort() without a compare Function (a compare function is a parameter accepted by sort()which helps to compare two values, to know which would come before which). This first method works well if you want to sort an array alphabetically.
/*sort this foodlist based on the firstletter*/
const foodList = ['plantain','beans','egg','rice','chips']
foodList.sort()
console.log(foodList)/*[ 'beans', 'chips', 'egg', 'plantain', 'rice' ]*/

As you can see in the code above, the array was sorted based on the position of the first letter alphabetically.

N/B: Sort() returns modify the initial array.

  • Method 2: In this method, sort accepts a compareFn as a parameter, and the compareFn also accepts two parameters(a, b)which will be used to compare two values.
    const scores = [80,4,10,55,100,30,45]
    scores.sort((a,b)=>{
    return a - b
    })
    console.log(scores)/*[  4, 10,  30, 45, 55, 80, 100]*/
    
if a - b = negative number ( a comes before b)
if a - b = positive number ( b comes before a)
if a - b = 0 (a is equal to b,so they have the same position)

So let's walk through the first example; a= 80 b=4 if (a - b; 80 - 4 =76) 76 is a positive number, so no matter what 4 will always be above a. (4 - 10 = -6) -6 is a positive number so 4 will come before 10. (10-55 = -45) -45 is a negative number so 10 will come before 55. This is the logic behind how these elements are being sorted accordingly.

reduce()

The easiest way to think of reduce is; having to make an array of different values finally come together resulting in one single value.

You can achieve this with a for loop or even with a forEach(). But the reduce() is the current method at the moment and it's more concise especially if you have to work with a whole lot of values. The reduce would have more use cases, but I'm just going to cover the basic concept. So you understand how it even works.

reduce() takes two parameters; a callbackFn and an initial value. The callbackFn takes in two parameters: the accumulator and the current value The accumulator holds the accumulated value of all the values in an array; say for instance you want to sum these numbers together(2+2+3+5+1+5). 2+2 = 4. 4 will be stored in the accumulator; So now when we need to add 3, we would do it this way accumulator + 3(4+3 =7) therefore accumulator at this point is equal to 7. So the value keeps on changing based on the operator that is used and the next value which is the current value refers to the next value in the array that is being added to the accumulator(ie if we were working with addition)

/*Example 1*/
/*provide the sum of numbers on this array*/

const scores = [80,4,10,55,100,30,45]
let sum = scores.reduce((prevValue,currValue)=>{
    return prevValue + currValue
})
console.log(sum)/*324*/
/*Example 2*/
/* We have an array of objects containing different dishes 
and their prices, print the sum of all the prices*/

const foodMenus = [
  {
    foodName: 'rice',
    price:500,
  },
  {
    foodName: 'dodo',
    price:1000,
  },
  {
    foodName: 'moimoi',
    price:200,
  },
  {
    foodName: 'chips',
    price:800,
  },
]
let prices = foodMenus.map((foodMenu)=>{
    let foodPrice =  foodMenu.price
    return foodPrice;
})
console.log(prices)/*[ 500, 1000, 200, 800 ]*/
let sumOfPrices = prices.reduce((prevValue,currValue)=>{
  return prevValue + currValue
})
console.log((sumOfPrices))/*2500*/

every( )

every( ) is an array method, that returns a boolean value(true or false). So you'd use every to check if all the values in an array fulfill a certain condition. If all the values fulfill a certain condition, the method will return a true value, if at least one doesn't fit into the category the method will return false.


/* Check if all the students in the class scored a B on the test
  B = score > 65
*/
const studentScores = [22,20,51,60,80,65,62]
studentScores.every( score => score >= 65)
/*false*/

const studentScores2 = [70,80,100,67,88]
studentScores2.every( score => score >= 65)/*true*/

The first example returned false because just a few students got a B on a test, not all or every single one of them. But as we can see on the second score array, all the students scored above 65 which passes the condition given by the function.

every( ) always returns true for an empty array.

some( )

some() works just like every method, it also returns a true or false value, depending on whether the array fulfills a specific condition. If at least one of the values in the array satisfies the condition stated in the function, it will return true. But if none of the values satisfy the condition it returns false.

some() always returns false for an empty array.


/* Check if all the students in the class scored a B on the test
  B = score > 65
*/
const studentScores = [22,20,51,60,80,65,62]
studentScores.some( score => score >= 65)/*true*/

The condition is asking for students that have scores that are equal to or greater than 65. In this array one person scored 65 and then only one other person had above 65, this means that the condition is satisfied, and at least one person was able to scale through, which makes the method return true for this condition.

includes( )

includes an array method that searches through an array to return a boolean value (true or false). Two parameters:

  • The search value

  • The index

The search value is the element in the array you want to search for, while the thefromindex parameter is the index you want to start the search for the element.

Array.includes(searchValue,fromindex)

If you do not specify thefromindex, the method automatically starts to search from the index[0].

const sweetNames= ['grace','cynthia','flavor']
sweetNames.includes('grace')/*true*/
sweetNames.includes('veronica')/*false*/
sweetNames.includes('grace',3)/*false*/
sweetNames.includes('cynthia',2)/*false*/

Now let's go through each result:

  • The first one returns true because we are searching the sweet names array from the index[0] and it contains the name 'grace' at index[0].

  • The second one returns false because it's very obvious that the name 'Veronica' doesn't appear in the array of sweet names.

  • The third one returns false because although 'grace' appears in the array, we stated that the search should begin from index 3. There is a rule here;

    If the from the index is greater than or equal to the array length, false will be returned in our case, the array length is 3 and the from the index is 3 as well, that is why the return value is false.

  • In the 4th case, the index value starts from index 2. And we are searching for 'Cynthia' which appears at index 1, so this will return a false value because Cynthia doesn't appear where the search is being made.

If the from index value is a negative number, we have to calculate a computed index using the array length and the negative from index value

const letters = ['a','b','c','d']
/*array length = 4*/
letters.includes('b', -80) /*true*/
letters.includes('b',-2)/*false*/
/* Formula: computed index = array.length + ( fromindex)
    4 + (-80) = -76
    4 + ( -2) = 2
  */

If your computed index is a negative number, then you can search the entire array, but if it's a positive number return false.

find( )

The find( ) method also helps us to search inside an array more like a private investigator.

It is really useful when you want to select a single element from an array.

Let's say we have a group of students named: Fola, Tosin, Chika, Tosin, Eliz, Fola, and Chika. And then you're asked to find Chika. In this case, let's say you opt to use the find( ) method, this method would search through the group of students and once it sees the first student named Chika, it will not look for any other Chika. If there was no Chika in the group of students, the method will return undefined.

/*Find the number less than 10*/
const numbers= [40,20,13,10,77,4,16,30,26,2,34,3]
let lowNumber = sweetNames.find( value=> value < 10)
console.log(lowNumber)/* 4*/

The example above wants us to find a number less than 10 from the array, but if you take a look at the array, we have 3 numbers less than 10, which are; 4,2,3.

So what the find( ) does is that it checks each element in the array and the very first one that satisfies the condition(ie less than 10) will be the one picked, and the rest wouldn't be used(i.e 2 and 3)

/* We have an array of Objects containing the information of some
 dancers in an academy, please help the dance instructor find
 the dancer with the dance style of Contemporary*/

const dancers = [
  {
    firstName:'Queendoline',
    age:22,
    dancestyle:'hiphop'
  },
  {
    firstName:'Diane',
    age:29,
    dancestyle:'cultural dance'
  },
  {
    firstName:'Ebuka',
    age:12,
    dancestyle:'hiphop dance'
  },
  {
    firstName:'Krystabel',
    age:25,
    dancestyle:'Contemporary'
  },
  {
    firstName:'Jacob',
    age:21,
    dancestyle:'Contemporary'
  },
  {
    firstName:'Sharon',
    age:7,
    dancestyle:'Ballet'
  },
]

let danceStyle =  dancers.find((dancer=>{
  return dancer.dancestyle === 'Contemporary'
}))
console.log(danceStyle)/*{ firstName: 'Krystabel', age: 25, dancestyle: 'Contemporary' }*/

Our console returns Krystabel's information because looking through the array, Krystabel's information as a contemporary dancer comes first and she is picked, so even though we have Jacob as a contemporary dancer in the array, it doesn't matter because Krystabel was captured first.

filter( )

filter( ) method acts like a basket, it helps us to sieve out the stuff we want into another basket. So let's say you have an array containing: oranges, apples, and peanuts, and then you want to take out the peanuts from the basket, you can use the filter method to achieve this fit.

filter( ) takes in a callback fn, and this callback fn will specify the condition that needs to be fulfilled by each element in the array, and if a particular element passes this condition, it is filtered out into a new array.

Let's use our example above with the dancers, this time around we need all the dancers on the list who know how to dance

const dancers = [
  {
    firstName:'Queendoline',
    age:22,
    dancestyle:'hiphop'
  },
  {
    firstName:'Diane',
    age:29,
    dancestyle:'cultural dance'
  },
  {
    firstName:'Ebuka',
    age:12,
    dancestyle:'hiphop'
  },
  {
    firstName:'Krystabel',
    age:25,
    dancestyle:'Contemporary'
  },
  {
    firstName:'Jacob',
    age:21,
    dancestyle:'Contemporary'
  },
  {
    firstName:'Sharon',
    age:7,
    dancestyle:'Ballet'
  },
]

let danceStyle =  dancers.filter(selectDancer)

function selectDancer(dancer){
  return dancer.dancestyle === 'Contemporary' 
}
console.log(danceStyle)/*[
  { firstName: 'Krystabel', age: 25, dancestyle: 'Contemporary' },
  { firstName: 'Jacob', age: 21, dancestyle: 'Contemporary' }
]*/

As you can see in the examples above, the console gives us only two dancers whose dance style is Contemporary dance. It filters them from the initial array into a new array called dance style.

There are a lot more array methods in Javascript, but these are the most common ones that I use and I'm sure every developer uses them as well. So therefore they are worth learning and understanding properly, why? Because they'd make your journey in Javascript so much easier.

Which method did you find the hardest to comprehend, and which did you find the easiest to comprehend, let me know in the comment section.