Array methods in Javascript

Swayam AllewarSwayam Allewar
5 min read

For more details Click here

What is an Array?

Arrays in programming world is a data-structure that allows you to store elements or data at contiguous location in memory. Long story short Arrays object in other programming languages enables storing collections of multiple items under single variable name. It has different member functions to perform operations on it

Arrays in Javascript are bit different!

In Javascript arrays are aren’t primitives but are objects with following properties:→

  • Javascript arrays are resizable can store mix data type but incase you want to store arrays for a specific datatype just be with this blog and you will end knowing how to do it .(Hint:Using typed arrays).

  • Arrays are not associative arrays so they can not accessed through any arbitrary strings and can only be accessed through non-negative indices .(Associative arrays are nothing but arrays which can be implemented as map, dictionary or like collection of key-value pairs and associative arrays use a key (which can be a string, number, or other data type, depending on the language) to access its corresponding value.

  • Arrays in Javascript are based on 0-based indexing which means the element of the array is at 0 th index ,1 st element at 1-index and so on and the last element is at the value of the array's length property minus 1.

  • Arrays in this language like other languages have multiple copy operations that results into shallow copies of the arrays. All standard built in javascript operations on object create shallow copies rather than deep copies.


Why do we need Arrays in Javascipt or any language altogether

Objects allow you to store keyed collections of values. That’s fine.

But quite often we find that we need an ordered collection, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.

It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.

There exists a special data structure named Array, to store ordered collections.


Implementation

  • To create an empty array there are two ways like as in the below code snippet and most of the time the other syntax is used more predominately
let arr=[];
console.log(arr)
let myArr=new Array();
console.log(myArr);
  • We can add elements to the array using square bracket
let fruits = ["Apple", "Orange", "Plum"];

Accessing elements at indices

let fruits = ["Apple", "Orange", "Plum"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
  • Altenative approach of doing this is by using EcmaScript 2022 new method i.e at() method

      let fruits = ["Apple", "Orange", "Plum"];
    
      // same as fruits[fruits.length-1]
      alert( fruits.at(-1) ); // Plum
    

Methods in Javascipt

  • Reversing an array - reverse() method

      let fruits = ["Apple","Orange","Plum"];
      fruits.reverse()
      // ['Plum', 'Orange', 'Apple']
    
  • Adding an element to array -push() method

    push method in javascript add specified elements to the end of the array

      let fruits = ["Apple","Orange","Plum"];
      fruits.push("Mango");
      // output
      // ['Apple', 'Orange', 'Plum', 'Mango']
    
  • Adding element to the start of the array-unshift()

      let fruits = ["Apple","Orange","Plum"];
      fruits.unshift("Mango");
      //['Mango', 'Apple', 'Orange', 'Plum']
    
  • Removing the elements at first index-shift()

    It also returns the value of element that was removed at index 0

      let fruits=["Apple","Orange","Plum"];
      fruits.shift();
      // 'Apple'
      console.log(fruits);
      // ['Orange', 'Plum']
    
  • some()→

    It is method of Array instances where it checks whether any of the element matches with the specified condition by the function if it passes returns a boolean value i.e True or False.

      let num=[1,2,2,4];
      console.log(num.some((ele)=>ele%2));
      // true
    
  • slice()→

    The slice method of Array instances is like where it returns a new array and it accepts parameter as start and end index that represents elements of the array. It does not monitor the original array.

      let num=[1,2,3,4]
      console.log(num.slice(1,2));
       // [2, 3]
    
  • sort()

    The sort function sorts the elements of the array in place and returns the sorted array with reference to same array, now sorted . The default sort order is ascending as it converts the elements to strings ,comparing sequence UTF-16 code unit values. If you don’t want to mutate original array then you can use toSorted()

      let num=[5,1,2];
      console.log(num.sort());
      //  [1, 2, 5]
      console.log(num.toSorted((a,b)=>b-a);
      // [5, 2, 1]
      // this does not change the original array
      console.log(num);
      //  [1, 2, 5]
    
  • toString()

    The toString function is method of Array instances converts the elements of the array to the string .

      let num=[1,15,6];
      console.log(num.toString());
    
  • with()

    It is function in which it replaces the element at given index with specified value .

      const arr = [1, 2, 3, 4, 5];
      console.log(arr.with(2, 6));
      // [1, 2, 6, 4, 5]
    
  • reduce()

    The reduce() method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

    The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

      const array1 = [1, 2, 3, 4];
    
      // 0 + 1 + 2 + 3 + 4
      const initialValue = 0;
      const sumWithInitial = array1.reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        initialValue,
      );
    
      console.log(sumWithInitial);
    

Conclusion

There are more methods in the Array instances which can be used for our purpose and I hope you were able to understand the all the methods

0
Subscribe to my newsletter

Read articles from Swayam Allewar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Swayam Allewar
Swayam Allewar