Understanding array methods in Javascript

Understanding array methods in Javascript

In this tutorial, we are going to cover what an array is, array methods, array iteration methods, and its basic operations. Array is a special type of object that allows you to hold more than one value. Let's say you have a list of items (a list of colors) that you want to store on independent variables. let color1 = "red"; let color2 = "blue"; let color3 = "white"; let color4 = "Orange"; Writing your code this way makes your work bulky and would bore you; this method is very difficult to maintain, but for simplicity and code readability, the best solution or practice is using an array.

let colors = [
    "red",
    "blue",
    "white",
    "orange",
];

This system or practice allows us to bypass the stress of creating four different variables; hence, we only need one variable to hold the colors listed above.

What is an array?

Array is a collection of data or values; each value is denoted as an element, and these elements are specified by an index. Arrays in javascript can be a number, string, boolean, or null. The javascript engine interprets words inside double quotes as strings, while an array that includes numbers, booleans, and null does not need to be quoted.

Creating an array

There are two ways of creating arrays in javascript: the array constructor method and the array literal notation. However, in this tutorial, we will primarily use the array literal notation. The purpose of the array constructor method is to create an entirely different array object or to set a new value for an existing array.

var courses = new Array ();
 console.log(courses);

Here, the list of courses displays an empty array because it doesn't have an element specified inside of it. To create an array, you need to initiate it with a list of elements.

Output

[]
var courses = new Array ("Geography", "English", "Mathematics");
 console.log(courses);

Output

(3) ['Geography', 'English', 'Mathematics']

However, the second example displayed a list of courses since some elements were initiated in the array given a total length of three indexes. Javascript counts from "0," which is why geography has an index number of zero, then ones and two, making three different elements in the array.

Array Literal Notation

The Array literal notation is the most commonly used array notation; here's how to use it.

var arrayLists = ["Value1", "Value2", "Value3", "Value4"];
console.log(arrayLists);

Output:

(4) ['Value1', 'Value2', 'Value3', 'Value4']

The literal notation allows us to wrap our elements inside square brackets [ ] with commas to separate the list of all the elements in the array. Let's create an array with a list of cars. Don't forget that strings should be quoted, but in case we fail to quote our string, let's see what we get as a result.

 let carNames = [Toyota, camry, Benz, Nissan];
console.log(carNames);

Output:

Toyota is not defined

The Javascript engine displays the first element as undefined; this works for every other element in the array because they are all strings and they should be quoted.

let carNames = ['Toyota', 'camry', 'Benz', 'Nissan'];
console.log(carNames);

Output:

 ['Toyota', 'camry', 'Benz', 'Nissan']

Note that it makes no difference whether a single or double quote is used.

How to access array elements

As was previously explained, in Javascript, the first element has index 0, the second element has index 1, the third has index2, and so on. Arrays are very centric about the position value of each element.

To access each element in the array, we need to get familiar with the array method.

Array method

The array method helps to eliminate the need for having to write a function from scratch by allowing us to access and make changes to the existing elements in the array. These methods are Javascript built-in functions that we can apply to our array; each method has its own unique function and effect.

Array Length(Size)

let carNames = ['Toyota', 'camry', 'Benz', 'Nissan'];
console.log(carNames.length);

Output:

4

The array length gives you the list of elements that are present in the array. These methods help when we want to iterate or loop through the array. It is possible that we will replace the value of the carNames element.

let carNames = ['Toyota', 'camry', 'Benz', 'Nissan'];
 carNames[2] = "bike"
 console.log(carNames);

Output:

['Toyota', 'camry', 'bike', 'Nissan']

In the third element, we altered the value from "Benz" to "bike" by calling out the index number, which is 2.

Basic Array Operation

a) IndexOf(Array)

This method is mostly useful when you’re building a TO-DO-LIST and you want to delete a task or any object, the indexOf method helps to display the position of a value in an array programmatically. This is beyond finding the length of an array.

var animals = ["Elephant", "Goat", "Hippopotamus", "Tiger", "Wolf"]
console.log(animals.indexOf("Goat"));

Output:

1

Keep in mind that if the value is present, the array's index position will be shown.

Conversion of Strings to Array

This javascript array method converts an array to a string of comma-separated values. See this for yourself:

console.log(Array.from("JAVASCRIPT"));

OUTPUT:

['J', 'A', 'V', 'A', 'S', 'C', 'R', 'I', 'P', 'T']

The entire string is now converted into an array (comma-separated values).

Pop & Push

When working on arrays, it is possible to remove elements or add a new element; that is where popping and pushing come in. The pop method is used to pop items out of an array, while the push method is used to push some items inside an array.

Array pop()

var animals = ["Lion", "Cow", "Elephant", "Shark", "Hippopotamus"];
 const lastItem = animals.pop();
 console.log(animals);

OUTPUT:

 ['Lion', 'Cow', 'Elephant', 'Shark']

When we apply the pop method, the final element "Hippopotamus" will be removed.

Array push()

The push method adds a new value to the list of elements at the end of the array.

 var animals = ["Lion", "Cow", "Elephant", "Shark", "Hippopotamus"];
 const wePush = animals.push("whale");
 console.log(animals);

OUTPUT:

['Lion', 'Cow', 'Elephant', 'Shark', 'Hippopotamus', 'whale']

Array Shift()

Shift is an array method that allows you to remove the first array element by shifting every other element to a minimal index.

var animals = ["Elephant", "Shark", "Hippopotamus"];
animals.shift();
console.log(animals);

OUTPUT:

["Shark", "Hippopotamus"]

Array Unshift()

The unshift method returns the new array element that was added.

 var animals = ["Lion", "Cow", "Elephant", "Shark", "Hippopotamus"];
 const method = animals.unshift("Goat");
 console.log(animals);
['Goat', 'Lion', 'Cow', 'Elephant', 'Shark', 'Hippopotamus']

Array Splice & Slice

The splice () method modifies the context of an array by adding or removing a new element from the existing array.

var animals = ["Elephant", "Shark", "Hippopotamus", "Tiger", "Cat"]
 const spliceMethod = animals.splice(3, 1,"Burberry", 655);
 console.log(animals);

A few things to note here:

The splice method is a little bit different from every other method because we need two or more parameters to specify the exact position we want to add or remove elements from. The first parameter determines where new elements should be spliced in (added), while the second parameter defines how many elements should be removed. Then the rest of the parameter is the new element to be added or inserted.

OUTPUT:

 ['Elephant', 'Shark', 'Hippopotamus', 'Burberry', 655, 'Cat']

The interpretation of this is to remove 1 element, starting from the third (3) index, which is "Tiger," and replace it with "Burberry," and 655

Slice() Method

The Slice method() is used to create a new array without removing any elements from the source array. Its syntax is as follows: In the javascript Slice method, we can specify where we want our slicing to begin; by default, the starting index will be zero, and the ending index is determined by the index of the last element in the array and where we want it to be sliced out.

 const animals = ["Elephant", "Shark", "Hippopotamus", "Tiger", "Cat"];
  const animal2 = animals.slice(1, 4);
console.log(animal2);

OUTPUT:

[ 'Shark', 'Hippopotamus', 'Tiger' ]

Slice(start) This parameter defines the position where new elements should be added; it is also known as "spliced in." Slice (end): This parameter defines the elements to be chopped off.

Array iteration Method

There is another lower deck of arrays that is known as the iteration method; these methods can operate on every item in an array consecutively. The most commonly used iteration methods include forEach(), filter(), map(), reduce(), reduceRight(), every(), some(), and lastly, find().

forEach() method

The Javascript forEach method calls back a given function for each element in an array. To achieve this, the forEach method requires three parameters, which are

  1. The element value (item value)

  2. The element index (item index)

  3. The array is the array on which the forEach () method must operate.

Let's write a code to support the following argument.

  var carLists = ["Toyota","Mercedes","Ferari","Chevrolet"];
   carLists.forEach(PrintNames => {
     console.log("Car lists : " , PrintNames);
   }) ;

OUTPUT:

 Car lists :  Toyota
 Car lists :  Mercedes
 Car lists :  Ferari
 Car lists :  Chevrolet

In the code above, we have an array containing four different elements. To print the name of each element of the car list, we used the javascript forEach() method.

filter() method

In Javascript, we have a method that can take a condition and use the condition to create a new array. The iteration method that creates a new array with the array element to achieve a given condition is the filter() method. Let's create a new list of arrays to filter out those with negative numbers.

const someNumbers = [-1, -2, -3, -4, -5, 0, 1, 2, 3, 4, 5];
const filtered = someNumbers.filter(function(value){
    return value < 0;
});
console.log(filtered);

OUTPUT:

 [-1, -2, -3, -4, -5]

Map() Method

The map method in javascript executes some function on each array and then creates a new array without tampering with the initial array. Take, for example, mapping each element in the phoneList array to add Huawei to each phone name listed.

 var phoneLists = ["Iphone", "Samsung", "Infinix", "Tecno"];
 var addNewProducts = phoneLists.map(AddName => {
     return AddName + "Huawei";
 });
 console.log("phoneLists : ", addNewProducts);

OUTPUT:

['IphoneHuawei', 'SamsungHuawei', 'InfinixHuawei', 'TecnoHuawei']

Reduce () Method

The javascript Reduce method performs a function on each element of the array and reduces it to only one value. With this method, we can reduce all the elements in the following array into a single value. This single value can be a number, object, or string, but in the case of this example we are going to use numbers.

const Output = [4, 3, 9, 10, 12, 14, 16];
 const newOutput = Output.reduce((accumulator, currentValue) =>{
     return accumulator + currentValue;
 }, 0);
 console.log(newOutput);

OUTPUT:

68

This function takes a callback function with two parameters: the total (accumulator) value and the current value. With this reduce method, we start with the accumulator, which can also be referred to as the total value, then loop through the output array and convert all the elements in the array to a single method.

ReduceRight () Method

Javascript's reduceRight method is the reverse of the reduce method; it works on each value to produce a single value, but in this case it works from right-to-left in the array. Let's make use of the following alphabet to see how the reverse works in the reduceRight method.

 const Output = ["b", "r", "e", "a", "d"];
 const newOutput = Output.reduceRight((accumulator, currentValue ) =>{
     return accumulator + currentValue;
 });
console.log(newOutput);

OUTPUT:

daerb

Every() Method

The every () method is a javascript iteration method used for testing every element in the array. It gives a return value of either true or false. We need to pass a callback function, and the values that we can use include a number, index, and array. See the code below to better understand how every element works in an array. We will write code to determine whether all of the elements in the array are even or odd numbers. var Output = [4, 9, 12, 16].every((a) => { return a%2 === 0; }); console.log(Output);

OUTPUT:

True

We got true as our output because every single element in the array gave us a result of true since they were all even numbers.

var evenNumber = (number) => { return number % 2 === 0; } var Output = [4,8,15,16].every(evenNumber); console.log(Output);

OUTPUT:

False

It gives us a result of false as output. This is because it is carrying out a test on the array, and if all the elements pass the test, it gives us true; otherwise, if any element fails the test, it displays false.

Some() Method

The Javascript Some() array checks if some of the elements in the array pass a test; if only a few of the array elements satisfy the given condition, then it displays an output of either Yes or No. Let's add a couple of numbers to the array that was used in the previous example.

const Output = [4, 3, 9, 10, 12, 14, 16].some((a) => {
     return a%2 === 0;
});
console.log(Output);

OUTPUT:

True

One good advantage of this iteration method is that it returns true even if we have odd numbers included in the array.

Find() Method

The find method only returns the value of the first element when a given condition is met, but if all the elements or some of the elements pass the test, the find method will only return the first value or element in the array.

const Output = [4, 3, 9, 10, 12, 14, 16].find((a) => {
     return a%2 === 0;
  });
   console.log(Output);

OUTPUT:

4

In some cases, if you set the array to perform a certain condition and all the elements fulfill the specified condition, it would return only the first element.

Conclusion

If you've read this far, you'll realize that array methods are one of the fundamentals of JavaScript. In this article, we learned about a few iteration methods such as the find() method, some() method, reduce() method, and so on. We also examined the two JavaScript methods for creating and indexing arrays as well as how to do so.