DEV Community

Cover image for An Intro To JavaScript Array Methods
Rajesh Ranjan
Rajesh Ranjan

Posted on • Edited on

An Intro To JavaScript Array Methods

Arrays are one of the most basic Data Structures in every programming language.
Every programmer must know the very basic concepts of array and how to use them efficiently. As arrays are already built-in in every programming language they are usually very efficient and are good choice to store and retrieve data easily.
Many programming languages provide built-in array methods to increase the efficiency of a programmer, JavaScript also provides as such built-in array methods which are very powerful.

Let's look at some of the important array methods in JavaScript

1. Array.push()

  //Use this method to add one element to the end of the array

  let fruitList = ['Mango', 'Apple', 'Orange', 'Banana']
  fruitList.push('Guava') 
  console.log(fruitList)
  Outputs: ["Mango", "Apple", "Orange", "Banana", "Guava"]
Enter fullscreen mode Exit fullscreen mode

2. Array.pop()

  //Removes only one element from the end of the array

  let fruitList = ['Mango', 'Apple', 'Orange', 'Banana', "Guava"]
  fruitList.pop() 
  console.log(fruitList)
  Outputs: ["Mango", "Apple", "Orange", "Banana"]
Enter fullscreen mode Exit fullscreen mode

3. Array.concat()

  //Merges two arrays and outputs a new array

  let odd_nums = [1, 3, 5, 7]
  let even_nums = [2, 4, 6, 8]
  const my_nums = odd_nums.concat(even_nums)
  console.log(my_nums)
  Outputs: [1, 3, 5, 7, 2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

4. Array.shift()

  //Removes one element from beginning

  let fruitList = ['Mango', 'Apple', 'Orange', 'Banana']
  fruitList.shift()
  console.log(fruitList)
  Outputs: ["Apple", "Orange", "Banana"]
Enter fullscreen mode Exit fullscreen mode

5. Array.join()

  //Returns a string out of an array by combining all the elements inside it

  let fruitList = ['Mango', 'Apple', 'Orange', 'Banana']

  const str1 = fruitList.join('')
  const str2 = fruitList.join(' ')
  const str3 = fruitList.join(',')
  console.log(str1, str2, str3)

  Outputs: "MangoAppleOrangeBanana"
            "Mango Apple Orange Banana"
            "Mango,Apple,Orange,Banana"
Enter fullscreen mode Exit fullscreen mode

6. Array.splice()

  //Returns a new array from an existing array by removing elements specified         
  by their index number

  let fruitList = ['Mango', 'Apple', 'Orange', 'Banana']

  //fruitList.splice(startAtIndex, numberOfElementsToRemove)

  const myFruits = fruitList.splice(0, 2)
  console.log(myFruits)

  Outputs: ["Mango", "Apple"]
Enter fullscreen mode Exit fullscreen mode

But this method also alters the base array which means the elements are literally removed from the base array.
If we do a console.log() from the base array we can see that:

  console.log(fruitList)
  Outputs: ["Orange", "Banana"]
Enter fullscreen mode Exit fullscreen mode

Here, we can see that "Mango" and "Apple" are removed from the base array too.
Array.splice() method is really a good method to add and remove elements from the array.

To add elements in the array using .splice() use this syntax:

   fruitList.splice(0, 2, "Papaya", "Strawberry", "Pears")
   console.log(fruitList)
   Outputs: ["Papaya", "Strawberry", "Pears", "Orange", "Banana"]
Enter fullscreen mode Exit fullscreen mode

So, how does this works at all?
To remove elements from the Array:- Array.splice() takes two arguments first
index to start removing the element and second the number of elements we want to remove. Here, we can see we have started from index 0 and removed 2 elements from the fruitList array.

To add elements to the array:- Array.splice() takes three parameters first and second arguments are used to specify the elements to remove starting from some index and number of elements to remove following the starting index. And, the third parameter is used to specify what elements to insert. We can use an array too as the third parameter.

   let fruitList = ['Mango', 'Apple', 'Orange', 'Banana']      
   const myFruits = ['Carrot', 'Guava', 'Peach']
   fruitList.splice(0, 2, ...myFruits) //ES6 spread operator
   console.log(fruitList)
   Outputs: ["Carrot", "Guava", "Peach", "Orange", "Banana"]
Enter fullscreen mode Exit fullscreen mode

Here, we can clearly see that the first two fruits are removed from the fruitList array and myFruits have in added at that place.
So, you will definitely say that what if I don't want to remove any fruits but I want to add my fruits to that fruitList also.
So, to do that simply make the second parameter 0, as we don't want any fruits to remove from the fruitList array.

let fruitList = ['Mango', 'Apple', 'Orange', 'Banana']
const myFruits = ['Carrot', 'Guava', 'Peach']
fruitList.splice(0, 0, ...myFruits) //ES6 spread operator
console.log(fruitList)
Outputs:["Carrot", "Guava", "Peach", "Mango", "Apple", "Orange", "Banana"]

Iterator Functions

These functions apply a function to each element of an array. And returns a value, a set of values, or a new array after applying the function to each element of an array.

7. Array.every()

This method applies a function to each element of the array and checks whether each element of the array satisfies the criteria of the defined function and returns a boolean value true or false based on the function definition.

  let nums = [2, 4, 6, 8]
  const isEven = nums.every((el) => {
  if (el % 2 == 0) return true
  else return false
  })
  console.log(isEven) //returns true
Enter fullscreen mode Exit fullscreen mode

Let's alter the nums array :-

  let nums = [2, 4, 6, 8, 5]
  const isEven = nums.every((el) => {
  if (el % 2 == 0) return true
  else return false
  })
  console.log(isEven) //will now return false
Enter fullscreen mode Exit fullscreen mode

Because in the first case all the numbers inside the nums array are even and all the numbers satisfy the function definition that each number must be divisible by 2. But, in second case we added an odd number which doesn't satisfy the function definition and return false.

8. Array.some()

This method is just opposite of above Array.every(). In this method if any one the element in the array satisfies the function definition then it returns a boolean value based on that criteria.

  let nums = [2, 4, 6, 8, 5]
  const isOdd = nums.some((el) => {
  if (el % 2 != 0) return true
  else return false
  })
  console.log(isOdd) //returns true
Enter fullscreen mode Exit fullscreen mode

As we can see the result is true which means there is at least one number in the array which is not DIVISIBLE by 2 and which means it is an odd number.

9. Array.map()

This method returns a brand new array out of the base array by applying the function to each element of the base array.
Let's see an example:-

  let fruitList = ['Mango', 'Apple', 'Guava', 'Papaya'];
  let eat = fruitList.map(fruit => {
     return `I want to eat ${fruit}`;
  })
  console.log(eat)

  Outputs: ["I want to eat Mango", "I want to eat Apple", 
           "I want to eat Guava", "I want to eat Papaya"]
Enter fullscreen mode Exit fullscreen mode

Let's see one more example:-

let nums = [2,4,6,8,10];
let squaredNums = nums.map(num => {
return Math.pow(num, 2);
})
console.log(squaredNums);
Outputs: [4, 16, 36, 64, 100]

10. Array.filter()

This method is some what similar to Array.every() but instead of returning a boolean value it returns a brand new array on the basis of the function definition. As the name suggests it filters out the elements from the array if the conditions are satisfied.
Let's see an example that filters out even numbers from the array:-

   let nums = [2,3,7,8,10,5]
   let filteredNums = nums.filter(num => {
      return num % 2 == 0;
   })
   console.log(filteredNums)
   Outputs: [2, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Let's see one more example to filter out numbers from the array which are greater than 15:-

let nums = [21,32,7,8,12,52,6]
let filteredNums = nums.filter(num => {
return num>15;
})
console.log(filteredNums)
Outputs: [21, 32, 52]

11. Array.reduce()

This method doesn't return a brand new array instead it returns a single value by applying the function to an accumulator and the successive elements of an array.

Let's take an array of numbers and we want to add all the numbers inside the array to get a total value. To achieve this we will use for loop

   let myNums = [1,2,3,4,5];
   let total = 0;
   for(let i=0;i<myNums.length;i++)
       total += myNums[i];
   console.log(total) //15
Enter fullscreen mode Exit fullscreen mode

But we can achieve the same result using the Array.reduce() method easily.

  let myNums = [1,2,3,4,5]
  const sum = myNums.reduce((a,num) => {
       return a+num;
  },0)
  console.log(sum) //outputs: 15
Enter fullscreen mode Exit fullscreen mode

The .reduce() method takes in three parameters, which are a (accumulator), num, and initial value, viz. 0 here.
What a does is that it takes in the initial value viz. 0 for now and keeps on adding the num from the array to the accumulator until the last index is reached in the array.

Let's see one more example:-

  let myNums = [1,2,3,4,5]
  const sum = myNums.reduce((a,num) => {
       return a+num;
  },10)
  console.log(sum) //now outputs 25
Enter fullscreen mode Exit fullscreen mode

Because we have assigned initial value to our accumulator as 10, so it starts adding the numbers to 10 and so on until the last index of array is reached.

12. Array.sort()

This method is really a simple method to sort the elements inside the array which are composed of alphabets. This method sorts the elements in a lexical order which is similar to the way in which we search a word in a dictionary. But, this method doesn't works with numbers.

Let's take an example to see how this method works:-

  let fruitList = ['Mango', 'Apple', 'Orange', 'Banana', "Guava"]
  let sortedFruits = fruitList.sort()
  console.log(sortedFruits)

  Outputs: ["Apple", "Banana", "Guava", "Mango", "Orange"]
Enter fullscreen mode Exit fullscreen mode

As we can clearly see the .sort() method has sorted our fruitList array
in alphabetical order.
But we can also use Array.sort() to sort our nums array too by passing a function to the Array.sort() method. And, what this function will do is that it will simply compare the nums in the array and sort them by following a simple rule viz.

If the number returned is negative, the left operand is less than the right operand, if the number returned is zero, the left operand is equal to the right operand and if the number returned is positive, the left operand is greater than the right operand.

Let's see the example:-

   let compareNums =(num1, num2)=> {
       return num1-num2;
   }
   let myNums = [5,27,85,4,78,32];
   const sortedNums = myNums.sort(compareNums)
   console.log(sortedNums)

   Outputs: [4, 5, 27, 32, 78, 85]
Enter fullscreen mode Exit fullscreen mode

So, we have seen some of the JavaScript array methods, there are many more such methods but these are some of the methods that are used regularly.

Top comments (0)