5 Essential Methods to Work with JS Arrays

5 Essential Methods to Work with JS Arrays

Table of contents

No heading

No headings in the article.

Arrays in JavaScript are a powerful data structure that developers can use to store and manipulate collections of values. Understanding how to work with arrays is critical whether you're creating a simple web page or a complex application. In this blog post, we'll look at 10 essential JavaScript array methods that will help you make use of javascript arrays.

  • ForEach()

    forEach() is a JavaScript built-in method that iterates over an array and executes a provided callback function once for each element in the array. The forEach() method does not return a new array, but it does have the ability to modify the original array.

      const numbers = [1, 2, 3, 4, 5];
      let sum = 0;
      numbers.forEach((number) => {
        sum += number;
      });
      console.log(sum); //output: 15
    
  • map()

    The map() method constructs a new array by applying a function to each element of the original array. It returns a new array of the same size as the original.

      const numbers = [1, 2, 3, 4, 5];
      const doubledNumbers = numbers.map((number) => {
        return number * 2;
      });
      console.log(doubledNumbers);  //output [2, 4, 6, 8, 10]
    
  • filter()

    The filter() method returns a new array containing all elements that satisfy a given condition. It accepts as a parameter a callback function that returns true or false for each element.

const numbers = [1, 2, 3, 4, 5];
const evenNumber = numbers.find((number) => {
  return number % 2 === 0;
});
console.log(evenNumber);  //output [2,4]
  • reduce()

    To reduce an array to a single value, use the reduce() function. It accepts as inputs a callback function and a starting value. The callback function accepts two arguments, the accumulator and the current value, and returns a new value for the accumulator.

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentElement) => {
  return accumulator + currentElement;
}, 0);
console.log(sum); //output: 15

every()

The every() method checks if every element of the array passes the condition specified to it. It returns true or false

const numbers = [1, 2, 3, 4, 5];
const areAllEven = numbers.every((number) => {
  return number % 2 === 0;
});
console.log(areAllEven); //output: false

Some bonus methods similar to every() :

1. some() - Returns true if any of the elements pass the condition

2. find() - Returns the first element that passes the conditions

3. includes() - Returns true if an array includes the value passed to it.

"Arrays are the Swiss Army Knife of programming. They store, sort, and simplify data, making our code more efficient and effective." - Addy Osmani

Did you find this article valuable?

Support Sai Lokesh Reddy by becoming a sponsor. Any amount is appreciated!