DEV Community

Cover image for Arrays and Array Methods in JavaScript
Bobate Olusegun
Bobate Olusegun

Posted on

Arrays and Array Methods in JavaScript

Let's say you're given the task of computing the test scores of all the students in your class who took maths and displaying the scores that are lower than the average. Your naïve method will be to first assign each student's score to a variable, then access each score by referencing the name of the variable, compute the average score, and check for scores below the average score. This strategy will make the program more difficult to use, and it will also break the DRY (Do Not Repeat Yourself) principle.
The use of a data structure known as an 'array' in JavaScript and other languages has resulted in a more efficient way of performing the task above. You can use an array to store all the scores of students who took maths in a list-like structure assigned to just one variable, and you can refer to any score using the variable name and index. For us programmers, the array makes life easier.

In this article, we'll learn how to create arrays in JavaScript and how to modify them with array methods. By the end of this session, you'll be able to apply the most often used array methods in JavaScript. This article is beginner-friendly, so don't worry if you know nothing about arrays in JavaScript. With that out of the way, let's get down to business with this tutorial.

Prerequisites

To follow along with this tutorial, you'll need the following:

  • Basic Knowledge of JavaScript
  • A text editor like Vs Code installed on your local desktop

What is an Array?

An array can be thought of as a large container that stores things of many types. The items in the large container can be referred to (i.e accessed later by a property each item possesses, which is the position).

Arrays In JavaScript

In JavaScript, an array is one of the most important data structures every JavaScript Developer must understand as well as be comfortable with its usage.

Arrays in JavaScript are ordered lists of values inserted between an opening square bracket ( [ ) and a closing square bracket ( ] ). Commas separate the list of values.

Example of an array in JavaScript:

let names = ["Moses" , "Jacob", "Isaac", "Abraham"]
console.log(names) // logs [ 'Moses', 'Jacob', 'Isaac', 'Abraham' ]
Enter fullscreen mode Exit fullscreen mode

Since JavaScript is not statically typed, an array in JavaScript can hold different types of data like the code below:

let main_arr = ["Isaac", "football", {name:"Moses"  , age: 21}, [one, two], 20]
Enter fullscreen mode Exit fullscreen mode

The code snippet above shows that arrays can hold data of different types. The array defined above contains different data types; strings, objects, array (YES!, an array can store another array), integer, and so on.

Creating Arrays

In JavaScript, we create arrays using two methods. They are:

  • Using Array constructor
//sysntax
let arr = new Array();
console.log(arr) //logs []
Enter fullscreen mode Exit fullscreen mode
  • Embedding elements within square brackets ([])
//syntax
//This is the most used method of creating arrays.
let arr = [];
console.log(arr) //logs []
Enter fullscreen mode Exit fullscreen mode

If you console log variable arr in the two code snippets above, you would notice that square brackets are returned. This simply means that the two methods are valid for creating arrays.

IsArray Method

JavaScript has a built-in method that checks if an item is an array. It returns true if the item passed to it is an array, otherwise, it returns false.

The implementation:

let programming_language = 'JavaScript';
console.log(Array.isArray(programming_language)); //logs false

let programming_languages = ['python', 'javaScript', 'java', 'golang'];
console.log(Array.isArray(programming_languages)); //logs true
Enter fullscreen mode Exit fullscreen mode

Length Vs Index

Indexing of arrays in JavaScript starts at zero. This statement means that the first element of an array is accessed using this numeric slot - arr[0]. The length of an array is the number of elements in an array. For example, the names array created above has four names embedded in it, meaning the number of elements of the names array is four, and the size of the array is four. In simple terms, the number of elements of an array is equal to the size or length of the array.

Let’s use a practical example to understand this better.

//let’s say we have an array with just one element.
let arr_new = ["JavaScript"];
//the number of elements of the arr_new array is one, so therefore the size of the array is one.
//In JavaScript we use the length method to get the size of an array

console.log(arr_new.length); //logs 1

//recall indexing starts at zero, to get the element in the arr_new array, we use the index
console.log(arr_new[0]); //logs JavaScript
Enter fullscreen mode Exit fullscreen mode

Note, in JavaScript, we use the indexof() method to get the index of a particular element in an array. If you use the indexof() method to check for the index of an existing element in an array, the index is returned otherwise it returns -1 (meaning the element doesn't exist in the array).

So far, we’ve learned how to create arrays, access the elements in an array, and also how to obtain the size of an array using the built-in length method that JavaScript provides for us.

Accessing Elements In an Array

Now that we know how to create an array in JavaScript, the question that comes to mind, is, how are the elements (values contained in an array) accessed. Essentially, numbers are used as lookup keys for arrays. The opening square bracket ( [ ) and closing square bracket ( ] ) notations are used to access a particular element in an array, by inserting the index number of that particular element in between the square brackets.

The code below will expain better on how to access element in an array:

//create an array
let names =  ["isaac", "samuel", "daniel", "moses"];
//In this instance, we want to access the second element of the names array
let names_access = names[1];
console.log(names_access) // logs samuel 
Enter fullscreen mode Exit fullscreen mode

Note, arrays in JavaScript are zero-indexed. This means the first element of an array is at position 0. In other words, to get an index of a particular element in an array, we start counting from zero and not from one.

Modify Elements In an Array

In JavaScript, we can modify elements in an array. The common application of array modification in JavaScript are:

  • Changing existing elements in an array.
//syntax
let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
//change the second element ('basketball') in the sports array to 'lawn tennis'
sports[1] = 'lawn tennis';
console.log(sports) //logs [ 'football', 'lawn tennis', 'Tennis', 'volleyball' ]
//change the second element back to 'basketball'
sports[1] = 'basketball';
console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
Enter fullscreen mode Exit fullscreen mode
  • Adding new elements to an array
//syntax
let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
//Since the array has elements in it, we can only add a new element at the end of the array
//You need to know the index of the last element in the array.
//The last index will be the length of the array - 1 because the positioning of elements starts from the index of zero.
//To get the number of elements in the sports array. We use the length method.
let sports_length = sports.length;
console.log(sports_length); //logs 4
//Now that we know the length of the array. The last index = length (which is 4) - 1.     //   //That's 3.
//So therefore the next element or the new element to be added be at index (last index +    //1), which is 4.
sports[4] = 'Lawn Tennis';
console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball', 'Lawn Tennis' ]
Enter fullscreen mode Exit fullscreen mode

Array Methods

Array methods in JavaScript are simply the set of built-in functions that enables us to manipulate or modify arrays. Arrays in JavaScript are mutable. In this section, you would learn and understand how to use array methods.The array methods are:

  • Pop Array Method
  • Push Array Method
  • Shift Array Method
  • Unshift Array Method
  • Slice Array Method
  • Splice Array Method
  • Map Array Method
  • Filter Array Method
  • Reverse Array Method
  • Concat Array Method
  • Join Array Method
  • Sort Array Method
  • Includes Array Method
  • Some Array Method
  • Every Array Method
  • Findindex Array Method
  • Find Array Method
  • ForEach Array Method
  • Reduce Array Method

Pop Array Method (array.pop())

This method is used to remove the last element in an array. You don't need to pass any argument into the parentheses.

The implementation:

 //syntax
 let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
 let sports_popped = sports.pop();
 console.log(sports);// logs [ 'football', 'basketball', 'Tennis' ]
 console.log(sports_popped); // logs volleyball
Enter fullscreen mode Exit fullscreen mode

Note, if you wish to remove more than just the last element, you have to call the pop() method as many times as you want to remove elements from the end of the array.

Push Array Method (array.push())

The push() method adds an element to the end of an existing array, then returns the length of the new array. This method takes in an argument, unlike the pop() method. The argument that's passed should be the element that you want to add at the end of the array.

The implementation:

//syntax
let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_pushed = sports.push('Lawn Tennis');
console.log(sports);// logs [ 'football', 'basketball', 'Tennis', 'volleyball', 'Lawn Tennis' ]
console.log(sports_pushed); // logs 5
Enter fullscreen mode Exit fullscreen mode

From the code snippet above, we can conclude that this method copies the elements in the
Original array, adds the new element to the list of elements. It then reassigns the variable of the old array to a new array with a list of the elements of the old array with an inclusion of the new element (pushed element).

Note, the push() method is an added feature; this feature enables you to add multiple elements to the end of the array at once.

//syntax
let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_pushed = sports.push('Lawn Tennis','cricket');
console.log(sports);// logs [ 'football', 'basketball', 'Tennis', 'volleyball', 'Lawn Tennis', 'cricket' ]
console.log(sports_pushed); // logs 6
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we used the push() method to add two elements to the end of the sports array.

Shift Array Method (array.shift())

This method removes the first element of an array. It's the opposite of the pop() method, as it removes the element from the beginning while pop() removes the element from the end of an array. The method also returns the element that was removed. This method is also similar to the pop() method in the sense that it doesn't take in any argument.

The implementation:

 let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
 let sports_shifted = sports.shift()
 console.log(sports); //logs [ 'basketball', 'Tennis', 'volleyball' ]
 console.log(sports_shifted); //logs football
Enter fullscreen mode Exit fullscreen mode

Note, if you wish to remove more than just the first element, you have to call the shift() method as many times as you want to remove elements from the beginning of the array.

Unshift Array Method (array.unshift())

This method adds an element to the beginning of an array. It's the opposite of the push() method. The method returns the length of the new array. This method is also similar to the push() method in the sense that it takes an argument, the argument should be the element you want to add to the array.

The implementation:

 let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
 let sports_unshifted = sports.unshift('Lawn Tennis');
 console.log(sports); //logs [ 'Lawn Tennis', 'football', 'basketball', 'Tennis', 'volleyball' ]
 console.log(sports_unshifted); //logs 5
Enter fullscreen mode Exit fullscreen mode

Note, if you use the unshift method without passing an argument, you don't get an error; there will be no difference in the elements of the array before and after the unshift method is applied.

The implementation:

 //before the unshift method is applied
 let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
 console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
 console.log(sports.length); // logs 4

 //after the unshift method is applied
 let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
 let sports_unshifted = sports.unshift()
 console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
 console.log(sports_unshifted); //logs 4
Enter fullscreen mode Exit fullscreen mode

Slice Array Method (array.slice())

This method returns a fragment of an existing array. It takes two numerical arguments which are indexes of existing elements in the array to which the method is applied. The first argument is the starting index (position) of elements that would be copied from the original array to the new array, while the second argument is the ending index (position) of elements that would be copied to the new array. The element at the position of the first argument is copied to the new array but the element at the position of the second argument is not copied to the new array. This means that the last element of the new array would be the element of the preceding index of the second argument in the original array. The method doesn't mutate the original array.

The syntax:
array.slice(start, end);

The implementation:

let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_sliced = sports.slice(1,3);
console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ], the original array still exist
console.log(sports_sliced); //logs [ 'basketball', 'Tennis' ]
Enter fullscreen mode Exit fullscreen mode

Note, if you use the slice method without passing an argument, you don't get an error; there will be no difference in the elements of the original array and new array. This also applies when zero is passed as the only argument.

The implementation:

let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_sliced = sports.slice();
let sports_one_sliced = sports.slice(0);
console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
console.log(sports_sliced); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
console.log(sports_one_sliced) //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
Enter fullscreen mode Exit fullscreen mode

Normally, you are expected to pass two arguments when using the slice method, but if you pass just one argument, JavaScript automatically takes that argument as the starting index and copies all elements from that index to the end.

The implementation:

let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_one_sliced = sports.slice(1);
let sports_two_sliced = sports.slice(2);
console.log(sports); //logs [ 'football', 'basketball', 'Tennis', 'volleyball' ]
console.log(sports_one_sliced); //logs [ 'basketball', 'Tennis', 'volleyball' ]
console.log(sports_two_sliced); //logs [ 'Tennis', 'volleyball' ]
Enter fullscreen mode Exit fullscreen mode

Splice Array Method (array.splice())

This method is used to replace, remove, and add a new element to an array. The splice() method takes in two arguments - starting index and delete count respectively. The elements are deleted from the starting index and the ending index is determined by the delete count.

The implementation:

let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_spliced = sports.splice(1,3);
console.log(sports); //logs [ 'football' ]
console.log(sports_spliced); // logs [ 'basketball', 'Tennis', 'volleyball' ]
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, the starting index is one, that is why the elements are deleted starting from the element in index one, and the ending index is three because the delete count is three; meaning delete three elements starting from index one, and that is the element at index one, index two and index three. The splice() method mutates the original array.

This method can also be used to add new elements to an array. In this instance, it takes starting index - like where you want to add the new elements, delete count - as zero (since nothing is expected to be deleted) and the elements you want to add, all separated with commas (',').

The implementation:

let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_spliced = sports.splice(3, 0, "lawn tennis", 'wrestling');
console.log(sports); //logs [
//   'football',
//   'basketball',
//   'Tennis',
//   'lawn tennis',
//   'wrestling',
//   'volleyball'
// ]
console.log(sports_spliced); // logs []
Enter fullscreen mode Exit fullscreen mode

Map Array Method (array.map())

The map() method creates a new array and populates it with the result of a callback function for each element in the original array. This method doesn't mutate the original array.

The implementation:

let numbers = [1, 2, 3, 4, 5, 6];

let triple_number = numbers.map(triple_nums);

//this is the callback function
function triple_nums(num) {
  return num * 3;
}

console.log(triple_number); //logs [ 3, 6, 9, 12, 15, 18 ]
console.log(numbers); //logs [ 1, 2, 3, 4, 5, 6 ], the original array still exist 
Enter fullscreen mode Exit fullscreen mode

Filter Array Method (array.filter())

The filter() method creates a new array that is populated by elements that satisfy the condition of the callback function.

The implementation:

//lets return even numbers
let numbers = [1, 2, 3, 4, 5, 6];

let even_nums = numbers.filter(even_numbers);
//this is the callback function
function even_numbers(num) {
  return num % 2 === 0; //the condition
}

console.log(numbers); // logs [ 1, 2, 3, 4, 5, 6 ]
console.log(even_nums); //logs [ 2, 4, 6 ]
Enter fullscreen mode Exit fullscreen mode

Under the hood, JavaScript will check if each element satisfies the condition. If an element in the array satisfies the condition, it resolves to True then it is passed to the new array, otherwise, it resolves to False and is not passed to the new array.

This method doesn't mutate the original array.

Reverse Array Method (array.reverse())

As the name implies, this method reverses the order of elements in an array. The first element becomes the last and the last element becomes the first. It returns a new array with elements having reversed order. This method mutates the original array.

The implementation:

//let's return the reversed order of the numbers array.
let numbers = [1, 2, 3, 4, 5, 6];

let reversed = numbers.reverse();

console.log(reversed); //logs [ 6, 5, 4, 3, 2, 1 ]
console.log(numbers); //logs [ 6, 5, 4, 3, 2, 1 ]
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, you would notice that the reversed array and numbers array are the same after the reverse() method has been applied.

Concat Array Method (array.concat())

This method merges multiple arrays (it can merge more than two arrays). The argument it takes is the array that is to be merged to the array the method is applied. This method doesn't mutate the original arrays.

The implementation:

//let's concatenate two arrays.
let nums_one = [1, 2, 3, 4, 5, 6];
let nums_two = [7, 8, 9, 10, 11, 12];

let nums_combined = nums_one.concat(nums_two);

console.log(nums_combined); //logs [
//     1,  2, 3, 4,  5,
//     6,  7, 8, 9, 10,
//    11, 12
//  ]
Enter fullscreen mode Exit fullscreen mode

In the explanation of what the concat() method is, I mentioned that we can use it to merge multiple arrays. When merging more than two arrays, you need to do the following:

  • Apply the concat() method to the first array
  • Pass the other two arrays as arguments for the concat() method
  • Separate the two arrays passed as arguments with a comma

Note, the list above applies when we want to merge three arrays.

The implementation:

//let's concatenate two arrays.
let nums_one = [1, 2, 3, 4, 5, 6];
let nums_two = [7, 8, 9, 10, 11, 12];
let nums_three = [13, 14, 15, 16, 17, 18];

let nums_combined = nums_one.concat(nums_two, nums_three);

console.log(nums_combined); //logs [
//     1,  2,  3,  4,  5,  6,  7,
//     8,  9, 10, 11, 12, 13, 14,
//    15, 16, 17, 18
//  ]
Enter fullscreen mode Exit fullscreen mode

Join Array Method (array.join())

The join() method creates and returns a string that comprises elements in an array, the elements are separated by commas - by default. The argument passed into the method stands as the separator of the elements of the array. The method doesn't mutate the original array.

Syntax
arr.join(separator);

The implementation:

//let's join elements of the array with a separator
let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let joined_sports = sports.join();
console.log(joined_sports); //logs football,basketball,Tennis,volleyball

//let's join elements of the array with a separator
let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let joined_sports = sports.join('-');
console.log(joined_sports); //logs football-basketball-Tennis-volleyball
Enter fullscreen mode Exit fullscreen mode

Sort Array Method (array.sort())

The sort() method simply sorts elements in an array in ascending order. It sorts strings using the first alphabet. The method loops through all elements in an array then compare them with each of their starting characters. This is how the method gets the element that would start the series of sorted elements. The method mutates the original array.

The implementation:

//let's sort elements of the sports array
let sports = ['football', 'basketball', 'tennis', 'volleyball'];
let sorted_sports = sports.sort();
console.log(sorted_sport); //logs [ 'basketball', 'football', 'tennis', 'volleyball' ]
console.log(sports); //logs [ 'basketball', 'football', 'tennis', 'volleyball' ]
Enter fullscreen mode Exit fullscreen mode

Note, the sort() method is case sensitive when using it make sure all the elements in the array the method is applied are consistent in lettering (i.e they are all starting with lowercase letters or they are all starting with uppercase letters).

Let's apply the sort() method to an array that has numbers as its elements.
The implementation:

//let's sort elements of the numbers array
let numbers = [7, 4, 6, 2, 3, 5, 1];
let sorted_numbers = numbers.sort();
console.log(numbers); //logs 
// [
//   1, 2, 3, 4,
//   5, 6, 7
// ]
Enter fullscreen mode Exit fullscreen mode

The sort() method doesn't sort an array with elements of one digit, two digits, and above.
For example:

//let's sort elements of the numbers array
let numbers = [70, 1, 100, 20, 35, 50, 11];
let sorted_numbers = numbers.sort();
console.log(numbers); //logs [
//     1, 100, 11, 20,
//    35,  50, 70
//  ]
Enter fullscreen mode Exit fullscreen mode

The code above shows that the sort() method uses the first alphabet or the first number of two digits or three digits number to sort an array with elements of numbers with more than one digit. In situations like this, we make use of the comparison function. Comparison function is a function that defines an alternative sort order.

The implementation of comparison function with sort() method:

//let's sort elements of the numbers array
let numbers = [70, 1, 100, 20, 35, 50, 11];
let sorted_numbers = numbers.sort(comparisonFunction);

function comparisonFunction(a, b) {
  return a-b;
}

console.log(numbers); //logs [
//     1, 11,  20, 35,
//    50, 70, 100
//  ]

//Alternatively if you want to have it in descending order, you simply do:
let numbers = [70, 1, 100, 20, 35, 50, 11];
let sorted_numbers = numbers.sort(comparisonFunction);

function comparisonFunction(a, b) {
  return b-a;
}

console.log(numbers); //logs [
//     100, 70, 50, 35,
//      20, 11,  1
//   ] 
Enter fullscreen mode Exit fullscreen mode

Includes Array Method (array.includes())

The includes() method checks if an element exists in an array. It returns true if the element exists in the array, otherwise false.

The implementation:

let sports = ['football', 'basketball', 'Tennis', 'volleyball'];
let sports_included = sports.includes('basketball');
let sports_not_included = sports.includes('lawn tennis');
console.log(sports_included); // logs true
console.log(sports_not_included); // logs false
Enter fullscreen mode Exit fullscreen mode

This method is case sensitive, whatever element you want to check for must be in the same letter case as the one that conforms with it in the array. This means that both elements must be either in uppercase or lowercase letters, or their first character must be either in uppercase or lowercase letters.

Some Array Method (array.some())

This method tests if at least an element in an array satisfies the condition passed by the callback function. If at least one element meets the criteria of the callback function, the result is resolved to true otherwise false.

The implementation:

//let's check if at least an element in the numbers array is even
let if_even = [2, 5, 6, 9, 11]; // we have at least two elements that are even
let if_not_even = [1, 3, 5, 9]; // there is no even number

let if_even_passed = if_even.some(even_numbers);
let even_not_passed = if_not_even.some(even_numbers);
//this is the callback function
function even_numbers(num) {
  return num % 2 === 0; //the condition
}

console.log(if_even_passed); // logs true 
console.log(even_not_passed); // logs false 
Enter fullscreen mode Exit fullscreen mode

Every Array Method (array.every())

This method tests if all elements in an array satisfy the condition passed through the callback function. Unlike the some() method, the every() method checks if all the elements of an array satisfy the condition in the callback function.
This method returns true if the elements in the array satisfy the condition in the callback function and false if the elements in the array don’t satisfy the condition.

The implementation:

//let's check if the the elements of the numbers array are all even
let if_even = [2, 4, 6, 8, 10];
let if_not_even = [1, 2, 3, 8, 10];

let if_even_passed = if_even.every(even_numbers);
let even_not_passed = if_not_even.every(even_numbers);
//this is the callback function
function even_numbers(num) {
  return num % 2 === 0; //the condition
}

console.log(if_even_passed); // logs true 
console.log(even_not_passed); // logs false 
Enter fullscreen mode Exit fullscreen mode

Note, all elements must satisfy the condition. IF some elements satisfy the condition, the result is still resolved to false.

Findindex Array Method (array.findIndex())

This method returns the index of the first element that satisfies the condition in the callback function.

The implementation:

let numbers = [1, 2, 3, 4, 5, 6];

function find_index(num) {
  return num >= 4;
}

let indexed_number = numbers.findIndex(find_index);
console.log(indexed_number); //logs 3
Enter fullscreen mode Exit fullscreen mode

Note, if no element in the given array satisfies the condition, an index of -1 is returned.
For example:

let numbers = [1, 2, 3, 4, 5, 6];

function find_index(num) {
  return num >= 7;
}

let indexed_number = numbers.findIndex(find_index);
console.log(indexed_number); //logs -1
Enter fullscreen mode Exit fullscreen mode

Find Array Method (array.find())

This method is similar to the findIndex(); the only difference is that the find() method returns the value of the first element that satisfies the condition in the callback function.

The implementation:

let numbers = [1, 20, 35, 40, 52, 6];

function find_value(num) {
  return num >= 10;
}

let found_number = numbers.find(find_value);
console.log(found_number); //logs 20 
Enter fullscreen mode Exit fullscreen mode

Unlike the findIndex() method which returns an index of -1 when no element satisfies the condition in the callback function, the find() method returns undefined if no element satisfies the condition in the callback function.

The implementation:

let numbers = [1, 20, 35, 40, 52, 6];

function find_value(num) {
  return num >= 60;
}

let found_number = numbers.find(find_value);
console.log(found_number); //logs undefined
Enter fullscreen mode Exit fullscreen mode

ForEach Array Method (array.forEach())

This method loops through an array. The method relies on a callback function on what should be done. The method takes three parameters: a value, an index, and an array.

The implementation:

let months = ['january', 'february', 'march', 'april', 'may', 'june'];

let months_aligned = months.forEach(month_display);

function month_display(month, index, arr) {
  console.log(`MOnth ${index + 1} - ${month}`); //In JavaScript, indexing starts from zero.
}

console.log(months_aligned); //logs MOnth 1 - january
// MOnth 2 - february
// MOnth 3 - march
// MOnth 4 - april
// MOnth 5 - may
// MOnth 6 - june
Enter fullscreen mode Exit fullscreen mode

We can use this method to perform the addition of numbers in an array.
The implementation:

let numbers = [1, 20, 35, 40, 52, 6]; 

let counter_sum = 0;

numbers.forEach((num) => {
  counter_sum += num;
})

console.log(counter_sum); //logs 154; that's the sum of all the elements in the numbers array. 
Enter fullscreen mode Exit fullscreen mode

Reduce Array Method (array.reduce())

As the name implies, this method reduces elements of an array to a single element. The method takes a callback function that is called in every iteration instance. This callback function has two arguments - an accumulator and a currentValue.
By default, the accumulator is set to the first value in the array while the currentValue is the second value in the array. The reduce() method takes either one or two arguments, the callback function or the callback function with the accumulator respectively.

The syntax: reduce method taking one argument

//es5 version
let arr = []; // the array we want to apply the reduce method

//callback function
function example(accumulator, currentValue) {
  //input what you want to perform with this callback function
}

let arr_reduced = arr.reduce(example); //the reduce method takes one argument(the callback function)

//es6 version(arrow functions)
let arr = []; // the array we want to apply the reduce method
let arr_reduced = arr.reduce((accumulator, currentValue) => {}) //the reduce method takes one argument(the callback function)
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, the accumulator will be set to the first value in arr because there is no defined value for the accumulator, while the currentValue will be the second value in arr.

The syntax: reduce method taking two arguments

//es5 version
let arr = []; // the array we want to apply the reduce method

//callback function
function example(accumulator, currentValue) {
  //input what you want to perform with this callback function
}

let arr_reduced = arr.reduce(example, acc_value); //the reduce method takes two argument(the callback function and accumulator intial value) 

//es6 version(arrow functions)
let arr = []; // the array we want to apply the reduce method
let arr_reduced = arr.reduce((accumulator, currentValue) => {}, acc_value) //the reduce method takes two argument(the callback function and accumulator intial value)
Enter fullscreen mode Exit fullscreen mode

Since the reduce() method takes a second argument - the accumulator, in the code snippet above, the accumulator is set to that defined value while the currentValue will be the first value in arr. The accumulator-defined value can be any value depending on your end goal, in most code snippets online, the accumulator-defined value is zero(0).

Let's practicalize with a basic problem of summing up numbers in an array

Use the reduce method to get the sum of numbers.

let numbers = [1, 20, 35, 40, 52, 6]; 

function sum_numbers(accumulator, currentValue) {
  console.log("The accumulator ", accumulator); //The accumulator  1 The accumulator  21 The accumulator  56 The accumulator  96 The accumulator  148
  return accumulator + currentValue;
}

 //since an accumulator is not defined, you will notice that the initial value of the accumulator is 1, that's because no accumulator was defined.

let result_val = numbers.reduce(sum_numbers);
console.log('The result is ',result_val); //logs 154
Enter fullscreen mode Exit fullscreen mode

You can condense the code above into this:

let numbers = [1, 20, 35, 40, 52, 6]; 
let result_val = numbers.reduce((accumulator, currentValue) => accumulator + currentValue , 0);
console.log(result_val); //logs 154
Enter fullscreen mode Exit fullscreen mode

let's use the reduce method with the ternary operator to find the number that is greater than all other numbers in the array

let numbers = [1, 20, 35, 20, 52, 6]; 

let greatest = numbers.reduce((accumulator, currentValue) => currentValue > accumulator ? currentValue : accumulator);
console.log(greatest);
Enter fullscreen mode Exit fullscreen mode

Note, it is not compulsory to name your variables as accumulator and currentvalue at all times. I just spelled out the name in full for easy grasp. You can shorten them to acc - accumulator and cur - currentValue.

Conclusion

In this article, we learned about array and array methods in JavaScript. First, we looked at some important information about arrays; like how to define or create arrays. Afterwhich we covered how to use some methods to check for an array and, modify arrays. Then, we explored the various important array methods (the ones you would need occasionally as a JavaScript developer).

For further reading check out the following:

You should also try out some leetcode easy array questions here

I hope you enjoyed this article as I anticipated, please like, leave a comment and, share this article.

Top comments (0)