Most important Array methods in Javascript

Most important Array methods in Javascript

There are multiple methods available to manipulate the values of the array in javascript. Arrays can hold the data in different format whether its elements, objects or nested objects and even nested arrays in the key value pairs. Also, there are some important methods that are introduced in ES6 feature of Javascript. Lets explore them in details.

  1. map():

    • Use Case: Transforming data in an array.

    • Example: Converting an array of Celsius temperatures to Fahrenheit.

        javascriptCopy codeconst celsiusTemperatures = [0, 10, 20, 30, 40];
        const fahrenheitTemperatures = celsiusTemperatures.map(temp => (temp * 9/5) + 32);
        // fahrenheitTemperatures: [32, 50, 68, 86, 104]
      
    • Often, you may need to transform data in an array into a different format.

        javascriptCopy codeconst products = [
            { name: 'Shirt', price: 20 },
            { name: 'Jeans', price: 30 },
            { name: 'Shoes', price: 50 }
        ];
      
        const prices = products.map(product => product.price);
        // prices: [20, 30, 50]
      
    • Rendering Lists: When working with frameworks like React, mapping over an array to render components is a common use case.

        javascriptCopy codeconst items = ['Apple', 'Banana', 'Orange'];
      
        const itemList = items.map((item, index) => <li key={index}>{item}</li>);
      
    • Generating IDs: You can generate unique IDs for array elements.

        javascriptCopy codeconst data = ['John', 'Doe', 'Alice'];
      
        const withIDs = data.map((item, index) => ({ id: index, name: item }));
        // withIDs: [{ id: 0, name: 'John' }, { id: 1, name: 'Doe' }, { id: 2, name: 'Alice
      
  2. filter():

    • Use Case: Filtering out elements from an array based on a condition.

    • Example: Filtering out even numbers from an array.

        javascriptCopy codeconst numbers = [1, 2, 3, 4, 5];
        const evenNumbers = numbers.filter(num => num % 2 === 0);
        // evenNumbers: [2, 4]
      
  • Data Filtering: Filtering out data based on specific criteria.

      javascriptCopy codeconst numbers = [10, 20, 30, 40, 50];
    
      const filtered = numbers.filter(num => num > 25);
      // filtered: [30, 40, 50]
    
  • Search Filtering: Filtering search results based on user input.

      javascriptCopy codeconst users = ['Alice', 'Bob', 'Charlie', 'David'];
    
      function filterUsers(query) {
          return users.filter(user => user.toLowerCase().includes(query.toLowerCase()));
      }
    
      const filteredUsers = filterUsers('b');
      // filteredUsers: ['Bob']
    
  • Removing Invalid Data: Filtering out invalid or empty entries from an array.

      javascriptCopy codeconst data = [null, undefined, 0, '', 'Hello', 42];
    
      const validEntries = data.filter(Boolean);
      // validEntries: ['Hello', 42]
    
  1. reduce():

    • Use Case: Aggregating data in an array into a single value.

    • Example: Calculating the total sum of values in an array.

        javascriptCopy codeconst numbers = [1, 2, 3, 4, 5];
        const sum = numbers.reduce((acc, curr) => acc + curr, 0);
        // sum: 15
      
  2. forEach():

    • Use Case: Iterating over each element of an array.

    • Example: Logging each element of an array.

        javascriptCopy codeconst fruits = ['apple', 'banana', 'orange'];
        fruits.forEach(fruit => console.log(fruit));
        // Output: apple, banana, orange
      
  3. find():

    • Use Case: Finding a specific element in an array.

    • Example: Finding the first even number in an array.

        javascriptCopy codeconst numbers = [1, 2, 3, 4, 5];
        const found = numbers.find(num => num % 2 === 0);
        // found: 2
      
  4. some():

    • Use Case: Checking if at least one element meets a condition.

    • Example: Checking if an array contains at least one negative number.

        javascriptCopy codeconst numbers = [1, 2, -3, 4, 5];
        const hasNegative = numbers.some(num => num < 0);
        // hasNegative: true
      
  5. every():

    • Use Case: Checking if all elements meet a condition.

    • Example: Checking if all elements in an array are positive.

        javascriptCopy codeconst numbers = [1, 2, 3, 4, 5];
        const allPositive = numbers.every(num => num > 0);
        // allPositive: true
      
  6. includes():

    • Use Case: Checking if an array contains a specific value.

    • Example: Checking if an array contains a certain string.

        javascriptCopy codeconst fruits = ['apple', 'banana', 'orange'];
        const hasBanana = fruits.includes('banana');
        // hasBanana: true
      
  7. slice():

    • Use Case: Extracting a portion of an array.

    • Example: Getting the first three elements of an array.

        javascriptCopy codeconst numbers = [1, 2, 3, 4, 5];
        const firstThree = numbers.slice(0, 3);
        // firstThree: [1, 2, 3]
      
  8. Array.from() Method:

    • Description: Creates a new array from an array-like or iterable object.

        javascriptlet str = 'JavaScript';
        let newArray = Array.from(str);
        console.log(newArray);
      
    • Output: ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']2.

  9. Array.of() Method:

    • Description: It creates an array with the specified elements. In ES5, when a single numeric value gets passed in the array constructor, then it will create an array of that size. Array.of() is a new way of creating an array which fixes this behavior of ES5.

      By using this method, if you are creating an array only with a single numeric value, then it will create an array only with that value instead of creating the array of that size.

        javascriptlet singleValueArray = Array.of(42);
        console.log(singleValueArray);
      
    • Output: [ 42 ]

These examples demonstrate the practical use of each array method to manipulate data and perform common operations on arrays in JavaScript.

Did you find this article valuable?

Support Ajinkya Chanshetty's Blog by becoming a sponsor. Any amount is appreciated!