Understanding JavaScript Array Methods

If you’re a JavaScript developer, then you should be familiar with the most commonly used ES5 and ES6+ array methods.

These methods make coding in JavaScript a lot easier and also make your code look clean and easy to understand to everyone….


This content originally appeared on DEV Community and was authored by Victor Ikechukwu

If you're a JavaScript developer, then you should be familiar with the most commonly used ES5 and ES6+ array methods.

These methods make coding in JavaScript a lot easier and also make your code look clean and easy to understand to everyone.

So in this article, we are going to explore some of the most important and widely used array methods used in JavaScript. So let's get started.

The Array.forEach Method

The Array.forEach method has the following syntax:

Array.forEach(callbackfn: (value: element, index: number, array: []))

The forEach method executes a provided callback function once for every element in the array.

const months = ['January', 'February', 'March', 'April', 'May', 'June'];
months.forEach(function(month) {
  console.log(month);
});

/* output
January
February
March
April
May
June
*/

Here's a Codepen Sample

Here, inside the forEach loop callback function, each element of the array is automatically passed as the first parameter of the function.

One important thing you need to keep in mind is that the forEach method does not return any value.

Take a look at the below code:

const workDays= ['Monday', 'Tuesday', 'Wednesday', 'Thursday'];
const returnedValue = workDays.forEach(function (day) {
  return day;
});

console.log('returnedValue: ', returnedValue); // undefined

Note that forEach is only used to loop through the array and perform some processing or logging. It does not return any value, even if you explicitly return a value from the callback function (this means that the returned value comes as undefined in the above example).

Advantages of using the Array.forEach Method

  • Using a forEach loop makes your code shorter and easier to understand
  • When using a forEach loop, we don't need to keep track of how many elements are available in the array. So it avoids the creation of an extra counter variable.
  • Using a forEach loop makes code easy to debug because there are no extra variables for looping through the array
  • The forEach loop automatically stops when all the elements of the array are finished iterating.

The Array.map Method

The Array map method is the most useful and widely used array method among all other methods.

The Array.map method has the following syntax:

Array.map(callbackfn: (value: element, index: number, array: []))

The map method executes a provided callback function once on every element in the array and it returns a new transformed array. that contains the results.

Take a look at the below code:

const workDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
const upperDays = workDays.map(function (day) {
  return day.toLocaleUpperCase();
});

console.log( upperDays); 
//output ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY','FRIDAY']

Here's a Code Sample

In the above code, inside the callback function, we’re converting each element to uppercase and returning it.

Using map method helps to avoid creating a separate converted array beforehand for storing the converted elements. So it saves memory space and also the code looks much cleaner using Array.map

Note that the map method returns a new array that is of the exact same length as the original array.

The difference between the forEach and map methods is that forEach is only used for looping and does not return anything back. On the other hand, the map method returns a new array that is of the exact same length as the original array.

Also, note that map does not change the original array but returns a new array.

The array map method is also useful if you want to extract only specific data from the array like this:

const workers = [
    {
        first_name: 'Mike',
        last_name: 'Sheridan',
        age: 30
    },
    {
        first_name: 'Tim',
        last_name: 'Lee',
        age: 45
    },
    {
        first_name: 'John',
        last_name: 'Carte',
        age: 25
    },
    {
        first_name: 'Paul',
        last_name: 'Victor',
        age: 22
    }
]

const workersAges = workers.map(function (user) {
    return user.age 
})

console.log(workersAges)
//output: [30, 45, 25, 22]

Here's a Code Sample

In the above code, we're extracting only the age of each worker and storing them in a new array.

Advantages of using the map method

  • It helps quickly generate a new array without changing the original array
  • It allows us to quickly extract any element of the array
  • It generates an array with the exact same length as the original array

The Array.find Method

The Array.find method has the following syntax:

Array.find(predicate: (value: element, index: number, array: []))

The find method returns the value of the first element in the array that satisfies the provided test condition. and undefined otherwise.

The find method takes a callback function (predicate) as the first argument and executes the callback function (predicate)for every element of the array. Each array element value is passed as the first parameter to the callback function.

Suppose, we have a list of employees like this:

const employees = [
    { name: "David Carlson", age: 32 },
    { name: "John Copper", age: 25 },
    { name: "Mike Sheridan", age: 24 },
    { name: "John Carte", age: 50 }
   ];

and we want to get the record for the employee whose age is less than 30. In this case, we can use the find method as shown below:

 const underAgeWorker= employees.find(function (employee) {
    return employee.age < 30 ;
  });

 console.log(underAgeWorker); 
// outputs: {name: "John Copper", age: 25}

Here's a Code Sample

Even though there is "Mike Sheridan" in the list whose age is also less than 30, the find method will stop when it finds the first match. So it will not return the first object with an age less than 30.

Advantages of using the find method

  • It allows us to quickly find any element without writing a lot of code
  • It stops looping as soon as it finds a match so there is no need for an extra break statement

The Array.findIndex Method

The Array.findIndex method has the following syntax:

Array.findIndex(callbackfn: (value: element, index: number, array: []))

The findIndex method returns the index of the first element in the array that satisfies the provided test condition. Otherwise, it returns -1, indicating that no element passed the test.

const employees = [
    { name: "David Carlson", age: 32 },
    { name: "John Copper", age: 25 },
    { name: "Mike Sheridan", age: 24 },
    { name: "John Carte", age: 50 }
   ];

const index = employees.findIndex(function (employee) {
  return employee.name.indexOf('John') > -1;
})

console.log(index); 
// outputs:  1

Here we get the output as 1 which is the index of the first object with the name John. Note that the index of an array starts with zero.

Advantages of using the findIndex method

  • It allows us to quickly find the index of an element without writing a lot of code
  • It stops looping as soon as it finds a match so there is no need for an extra break statement

The Array.filter Method

The Array.filter method has the following syntax:

Array.filter(callbackfn: (value: element, index: number, array: []))

The filter method takes a callback function as the first argument and executes the callback function for every element of the array and returns a new array with all the elements that meet the condition specified in the callback function.

So using the filter method, it does not stop when it finds a particular match but keeps checking for other elements in the array that match the condition. Then it returns all the matching elements from the array.

const employees = [
    { name: "David Carlson", age: 30 },
    { name: "John Cooper", age: 24 },
    { name: "Mike Sheridan", age: 25 },
    { name: "John Carte", age: 50 }
   ];

   const employee = employees.filter(function (employee) {
    return employee.name.indexOf("John") > 1 ;
  });

console.log(employee)
//output [ { name: "John Cooper", age: 24 }, { name: "Mike Sheridan", age: 25 } ]

Note that the filter method always returns an array. If no element passes the test condition, an empty array will be returned.

Advantages of using the filter method

  • It allows us to quickly find all the matching elements from the array
  • It always returns an array even if there is no match, so it avoids writing extra if conditions
  • It avoids the need of creating an extra variable to store the filtered elements

The Array.every Method

The Array.every method has the following syntax:

Array.every(callbackfn: (value: any, index: number, array: []))

The every method tests whether all elements in the array pass the provided test conditions and returns a boolean true or false value.

Imagine you have a registration form, and you want to check if all of the required fields are entered or not before submitting the form. You can use the every method to check for each field value easily.
Here's a Code Sample

Advantage of using the every method

  • It lets us to quickly check if all the elements match certain criteria without writing a lot of code

The Array.reduce Method

The Array.reduce method has the following syntax:

Array.reduce(callbackfn: (accumulator: any, currentValue: any, Index: number, array: []), initialValue)

The reduce method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Note that the output of the reduce method is always a single value. It can be an object, a number, a string, an array, and so on. It depends on what you want the output of reduce method to generate but it's always a single value.

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(function(accumulator, number) {
  return accumulator + number; 
}, 0);

console.log(sum); // 15

The reduce method accepts a callback function that receives accumulator, number, index and array as the values. In the above code, we’re using only accumulator and number.

The accumulator will contain the initialValue to be used for the array. The initialValue decides the return type of the data returned by the reduce method.

The number is the second parameter to the callback function that will contain the array element
during each iteration of the loop.

In the above code, we have provided 0 as the initialValue for the accumulator. So the first time the callback function executes, the accumulator + number will be 0 + 1 = 1 and we're returning back the value 1.

The next time the callback function runs, accumulator + number will be 1 + 2 = 3 (1 here is
the previous value returned in the last iteration and 2 is the next element from the array).

Then, the next time the callback function runs, accumulator + number will be3 + 3 = 6 (the first 3 here is the previous value returned in the last iteration and the next 3 is the next element from the array) and it will continue this way until all the elements in the numbers array are not iterated.

So the accumulator will retain the value of the last operation just like a static variable.

In the above code, initialValue of 0 is not required because all the elements of the array are
integers.

Advantages of using the reduce method

  • Using reduce allows us to generate any type of simple or complex data based on the array
  • It remembers the previously returns data from the loop so helps us avoid creating a global variable to store the previous value

Thanks so much for reading!

thank-you.gif

*That's all from me guys. hoped you've learned a little bit about the awesome JavaScript Array and its methods *

If you still have any questions, don't hesitate to reach out in the comments section below!

Want to stay up to date with regular content regarding JavaScript, Python, And How to code in general? Follow me on Twitter .

**Enjoyed reading this as much as i enjoyed writing it for you? ?** . support me with a coffee ? Buy Me A Coffee


This content originally appeared on DEV Community and was authored by Victor Ikechukwu


Print Share Comment Cite Upload Translate Updates
APA

Victor Ikechukwu | Sciencx (2021-06-16T00:49:33+00:00) Understanding JavaScript Array Methods. Retrieved from https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/

MLA
" » Understanding JavaScript Array Methods." Victor Ikechukwu | Sciencx - Wednesday June 16, 2021, https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/
HARVARD
Victor Ikechukwu | Sciencx Wednesday June 16, 2021 » Understanding JavaScript Array Methods., viewed ,<https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/>
VANCOUVER
Victor Ikechukwu | Sciencx - » Understanding JavaScript Array Methods. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/
CHICAGO
" » Understanding JavaScript Array Methods." Victor Ikechukwu | Sciencx - Accessed . https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/
IEEE
" » Understanding JavaScript Array Methods." Victor Ikechukwu | Sciencx [Online]. Available: https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/. [Accessed: ]
rf:citation
» Understanding JavaScript Array Methods | Victor Ikechukwu | Sciencx | https://www.scien.cx/2021/06/16/understanding-javascript-array-methods/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.