Need To Know JavaScript Array-Methods

Introduction

If you have been learning and using JavaScript for a while now and always messing with different ways to use array methods, you are in the right place because will be discussing the commonly used array methods and giving some straightforward examples so you can get started right away.

Background

Just to give you an idea about my experience with JavaScript arrays, I thought that I needed to learn almost everything about it but in reality, you won’t be using every single method in a certain project. However, knowing everything doesn’t hurt but I do suggest that learning the commonly used ones will get you started and be productive. OK, then let’s get started.

In this post, we are going to discuss the following array methods

  • map
  • filter
  • find
  • some
  • every
  • reduce
  • include

Before we start with every method mentioned in the list above. See the array declaration below that will be used for the entire method examples.

const employees = [
    {
        employee: 'Eleanor R. Crane',
        company: 'Tellus Faucibus Leo Incorporated',
        salary: 15200
    },
    {
        employee: 'Haviva E. Lane',
        company: 'Eu Neque Pellentesque Incorporated',
        salary: 13333
    },
    {
        employee: 'Merrill F. Morrison',
        company: 'Lobortis Quam Ltd',
        salary: 1450
    },
    {
        employee: 'Halee L. Hensley',
        company: 'Elit Corp.',
        salary: 15872
    },
    {
        employee: 'Hamish T. Trevino',
        company: 'Rhoncus LLC',
        salary: 14214
    }
];

Map

This method returns a new set of arrays but doesn't change the original array.

// syntax: array.map(function(currentValue, index, currentArray), thisValue)
/**
 * I want to know the list of companies where the employees work.
 */
const companies = employees.map((currentEmployee) => {
    return currentEmployee.company;
});

/**
 * Output:
 * 0: "Tellus Faucibus Leo Incorporated"
 * 1: "Eu Neque Pellentesque Incorporated"
 * 2: "Lobortis Quam Ltd"
 * 3: "Elit Corp."
 * 4: "Rhoncus LLC"
 */
console.log(companies);

Filter

This method returns a new set of arrays that will pass a certain implemented test within the provided function.

// syntax: array.filter(function(currentValue, index, currentArray), thisValue)
/**
 * I want to get the employees having a salary of more than 15k.
 */
const highSalary =  employees.filter((currentEmployee) => currentEmployee.salary >= 15000);  

/**
 * Output:
 * 0: {employee: "Eleanor R. Crane", company: "Tellus Faucibus Leo Incorporated", salary: 15200}
 * 1: {employee: "Halee L. Hensley", company: "Elit Corp.", salary: 15872}
 */
console.log(highSalary);

Find

This method returns the first element that satisfies the implemented test within the provided function.

// syntax: array.find(function(currentValue, index, currentArray), thisValue)
/**
 * I want to get the first employee having a salary of more than 15k.
 */
const firstEmployeeWithHighSalary = employees.find((currentEmployee) => currentEmployee.salary >= 15000);  

/**
 * Output:
 * {  
 *   company: "Tellus Faucibus Leo Incorporated" 
 *   employee: "Eleanor R. Crane" 
 *   salary: 15200 
 * }
 */
console.log(firstEmployeeWithHighSalary);

Some

This method returns a boolean value and returns true when at least one of the elements inside the array passes the test implemented within the provided function else false.

// syntax: array.some(function(currentValue, index, currentArray), thisValue)
/**
 * I want to check if any employee name starts with letter H.
 */
const hasEmployeeNameStartsWithLetterH = employees.some((currentEmployee) => currentEmployee.employee.startsWith("H"));

/**
 * Output: true
 */
console.log(hasEmployeeNameStartsWithLetterH);

/**
 * I want to check if any employee name starts with letter A.
 */
const hasEmployeeNameStartsWithLetterA = employees.some((currentEmployee) => currentEmployee.employee.startsWith("A"));

/**
 * Output: false
 */
console.log(hasEmployeeNameStartsWithLetterA);

Every

This method returns a boolean value and returns true when all elements within the array pass the test implemented within the provided function else false.

// syntax: array.every(function(currentValue, index, currentArray), thisValue)
/**
 * I want to check if all employee's salaries are below 16k.
 */
const everyEmployeeHasSalaryLessThan16K = employees.every((currentEmployee) => currentEmployee.salary <= 16000);

// output: true
console.log(everyEmployeeHasSalaryLessThan16K);

Reduce

This method returns a single value that results from the reducer function that you have provided on each element of the array.

// syntax: array.reduce(function(total, currentValue), initialValue)
/**
 * In our case, the initial value equals zero.
 * Then the accumulator, which is defined as totalSalary, will hold the initial and previous values within the array.
 * The sequence looks like this:
 * 0 + 15200 + 13333 + 1450 + 15872 + 14214 === 60069
 */
const totalSalaryOfEmployees = employees.reduce((totalSalary, currentEmployee) => {
    return totalSalary + currentEmployee.salary;
}, 0);

// output: 60069
console.log(totalSalaryOfEmployees);

Include

This method checks whether an array contains a specified element that returns true if does exists else false.

Note. We will be using different array declarations. The usage includes

const banks = ["HSBC", "Wells Fargo", "Bank of China", "Union Bank"];
const doesHSBC_exists = banks.includes("HSBC");
console.log(doesHSBC_exists);

Summary

In this article, we have discussed the following:

  • map
  • filter
  • find
  • some
  • every
  • reduce
  • include

I hope you have enjoyed this article, as I have enjoyed writing it. Until next time, happy programming!

References

Array - JavaScript - MDN Web Docs - Mozilla