5 of the Most useful javascript Array API

1. Array.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function

  • let’s say you have an array with several elements and you need to filter out that array based on some parameter/condition.
  • In this case, we have an array of numbers that need to filter based on the condition that a given element should be divisible by 3.
  • We could just use the filter() API on that array.

As Method suggests if the given elements in the array satisfy the given condition then those elements will be returned from the array.

2. Array.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

  • let’s say you have an array with several elements and now this time instead of filtering the elements you need to perform some operations on the elements and get a new array from the results.
  • In this case, we have an array of numbers from that need array with the square of each element.
  • We could just use the map() API on that array.

3. Array.unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

  • Many of the naive developers write lines of code to put an element at the start of the array(I was one of them 🤪).
  • No worries unshift() is here to rescue you. It takes the n number of parameters and puts it at the start of the array in the given sequence.

4 Array.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.

  • This one is my favorite, there are some use cases where you need to check whether any(some) element in an array satisfy the given condition or not.
  • some() method returns a boolean value based on the given condition, in the following example, we will check if our array contains any even number.

There is a similar API that returns true if all the elements satisfy the given condition Array.every()

5 Array.flat()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

  • Many times I faced the issue where I have the recursive array from that I need a single array with up to a specific depth of the element.
  • What flat() method does it takes a number(depth) as an argument(default to 1) and then returns the single array recursively up to the given depth.

These are the 5 API that I Love most, there are plenty of API in Javascript Array that use can use, you can check the rest of the API’s here.

Originally published at https://adarsh-thakur.hashnode.dev.

Hey 👋, I am Adarsh, a Web Developer from 🇮🇳