Javascript Array Methods

Prerequisites

For one to follow along with this blog post and imbibe, you need to be familiar and understand with fundamentals of JavaScript.

For practicing code implementation, you should also have an IDE like VSCode, Sublime, Bracket, Atom, etc.

In this article, we examine the best ways to comprehend and assimilate what an Array Data Structure is. Adopting a portion of the strategy, even if you don't employ it entirely, can be helpful in and of itself.

What is Array Data Structure?

A linear data structure called an array contains elements of the same data type in contiguous and nearby memory regions. Arrays operate using an index system with values ranging from 0 to (n-1), where n is the array's size.

Types of Arrays

There are primarily two different kinds of arrays:-

  • Single Dimensional Arrays

If required, a JavaScript one-dimensional array is used to store numerous values of various data types in a single variable.

Create using New Keyword

The new keyword can be used to build an array, just like it can be a string or an integer.

  <!DOCTYPE html>
  <html>
  <body>

  <script>
  var myCar = new Array('Aston Martin', 'Jaguar', 'Porche');
  document.write('I love '+myCar[1]);
  </script>
  </body>
  </html>
  • Multiple-Dimensional Arrays

Native support for the multidimensional array is not available in JavaScript. However, you can define an array of elements where each member is likewise an array in order to construct a multidimensional array.

Because of this, we may say that a multidimensional array in JavaScript is an array of arrays. The array literal notation is the simplest way to define a multidimensional array.

The same syntax as declaring a one-dimensional array is used to declare an empty multidimensional array:

let activities = [];

An activities two-dimensional array is defined by the example below:

let activities = [
['commute', 3],
['Sleep', 8],
['Work', 10],
['Play Game', 1],
['Eat', 2]
];

The first dimension in the activities array denotes the activity, while the second one displays how many hours a day are spent on each.

You may use the console.table() method as follows to display the activities array in the console:

console.table(activities);

The result is illustrated by the following:

┌─────────┬─────────────┬───┐
 (index)       0       1 
├─────────┼─────────────┼───┤
    0       'Commute'  3 
    1        'Sleep'   8 
    2      'Work'      10
    3     'Play Game'  1 
    4       'Eat'      2 
└─────────┴─────────────┴───┘

In the picture, the (index) column shows the indices of the inner array; take note of this.

You must use square brackets to access an element of the outer array that returns an inner array before using another square bracket to access the element of the inner array in order to access a multidimensional array element.

The activities array's first inner array's second member is returned by the example that follows:

  console.log(activities[0][1]); // 9

Why do we use Arrays?

  1. As a more condensed alternative to (otherwise repetitious) many IF statements, we utilize arrays to detect if control flow in programs is partial or complete. They are used in conjunction with a specially designed interpreter whose control flow is modified in accordance with values stored in the array and are referred to in this context as control tables. The execution path can be determined by subroutine pointers (or relative subroutine numbers that can be affected by SWITCH instructions) contained in the array.

  2. Mathematical vectors, matrices, and other sorts of rectangular tables are all implemented using arrays. Many databases, whether small and big, are made up of (or include) one-dimensional arrays with records as their constituent elements.

  3. Other data structures including lists, heaps, hash tables, deques, queues, stacks, strings, and VLists are implemented using arrays. When compared to tree-based data structures, array-based implementations of other data structures are usually straightforward and small in size (implicit data structures), needing little space overhead (compare a sorted array to a search tree).

Why do we need Array in Data Structure?

Consider a class of ten pupils that is required to report its findings. It would be difficult to manipulate and preserve the data if you had specified each of the ten variables separately.

It would be more challenging to declare and maintain track of all the variables if more students joined. Arrays were introduced as a solution to this issue.

Benefits of using Array Methods

  • They make it simple to access each element at once, regardless of which element is accessed first.

  • When creating an array, you don't need to worry about memory allocation because all elements are given memory in the array's contiguous memory locations. If there is an array, there is no probability that additional memory will be allocated. This prevents the problem of excess or deficiency of memory.

  • Arrays can be used to create other types of data structures, including linked lists, stacks, queues, trees, and graphs. They can also be used to implement different CPU Scheduling strategies.

  • Code maximization can be useful. We can put a lot of values in an array by writing a tiny bit of code.

Accessing an element in an array requires a fixed amount of time, or O(1) time complexity.

Matrix representations are made using two-dimensional arrays.

  • Array indices begin with "0," as opposed to other data structures, which begin with "1."

  • There is no maximum number of times an array can be used.

  • Within an existing array, new subarrays can be simply created by a computer.

  • If it is necessary to alter the value kept at a particular place, it is possible to do so without altering the array's complete contents.

  • An array makes it simple to apply algorithms for searching, sorting, and finding maximum and minimum values.

Common Array Methods

  • Array fill()

With the help of examples, we will learn about the JavasScript Array fill() method in this lesson.

The fill() method creates an array by assigning a specific value to each element before returning it.

Example

   // defining an array 
   var fruits = ['Pine-apple', 'Papaye', 'Grape'];

   // filling every element of the array with 'Cherry'
   fruits.fill("Cherry");

   console.log(fruits);

  // Output: 
  // [ 'Cherry', 'Cherry', 'Cherry' ]

fill() Syntax

The syntax of the fill() method is:

 arr.fill(value, start, end)

Here, arr is an array.

fill() Parameters The fill() method can take 3 parameters:

  • value - Value to fill the array with.
  • start (optional) - Start index (default is 0).
  • end (optional) - End index (default is Array.length), which is always excluded.

fill() Return Value

  • Returns the modified array, filled with value from start to end.

Notes:

  • Indexes are counted backwards if start or end are negative numbers.
  • Given that fill() is a mutator method, the array is changed (rather than copied) before being returned.

Example 1: Using fill() Method

var prices = [800, 53, 8, 2, 5];

// filling every element of the array with '5'
new_prices = prices.fill(5);

console.log(prices);

console.log(new_prices); 

Output

       [ 5, 5, 5, 5, 5 ]
       [ 5, 5, 5, 5, 5 ]

In the aforementioned illustration, we filled each entry of the prices array with 5 using the fill() method.

The method was called with the number 5 as the fill value, and new prices was given the return value.

Due to the fact that prices.fill(5) affects the initial array and is a mutator, both prices and new prices contain the same value.

Example 2: fill() Method with Three Arguments

    // array definition
    var language = ["JavaScript", "Python", "C#", "Java"];

    // replacing element of array from index 1 to 3 by 'JavaScript'
    language.fill("JavaScript", 1, 3);

   // printing the original array
  console.log(language);

Output

   [ 'JavaScript', 'JavaScript', 'JavaScript', 'Java']

Here, we've used the fill() method to fill the language field with "JavaScript" from index 1 to 3. (excluding 3).

Therefore, the procedure simply substitutes "JavaScript" for the language[1] and language[2] elements.

Example 3: fill() Method with Invalid Indexes

 var rank = [9, 7, 4, 8];

 // on passing negative index, counting starts from back
 rank.fill(18, -4);

 // prints the modified 'rank' array
 console.log(rank);  // [ 9, 7, 18, 18 ]

// passing invalid index result in no change
rank.fill(18, 8, 9);

console.log(rank);  // [ 9, 7, 18, 18 ]

// passing invalid indexes
rank.fill(18, NaN, NaN);

console.log(rank);  // [ 9, 7, 18, 18 ]

Output

[ 9, 7, 18, 18 ]
[ 9, 7, 18, 18 ]
[ 9, 7, 18, 18 ]

In the aforementioned example, we called the fill() method and gave a negative index value of -4 as start. The remaining two entries of the array are filled with 18 via rank.fill(18,-4).

If the start and end index values are more than the array size, rank.fill(18, 9, 7); rank.fill(15, NaN, NaN);

In this case, the indexes 8, 9, and NaN, NaN are invalid, therefore the procedure returns the array unchanged.

Array pop()

The JavaScript Array push() method will be covered in detail in this lesson using examples.

The last element in an array is removed by the pop() method, which then returns the removed element.

Example

let cities = ["Dallas", "Los Angeles", "Chicago", "Manchester"];

// remove the last element
let removedCity = cities.pop();

console.log(cities)         // ["Dallas", "Los Angeles", "Chicago"]
console.log(removedCity);   // Manchester

pop() Syntax The syntax of the pop() method is:

 arr.pop()

Here, arr is an array.

pop() Parameters The pop() method does not have any parameters.

pop() Return Value returns the value after removing the final element from the array. If the array is empty, the result is undefined.> Notes:

  • This method changes the original array and its length.
  • Use the JavaScript Array shift() method to get rid of the array's first element. Example: Using pop() method
  var languages = ["JavaScript", "Python", "Java", "C#", "Lua"];

  var popped = languages.pop();

  console.log(languages); // [ 'JavaScript', 'Python', 'Java', 'C#' ]
  console.log(popped); // Lua

  // pop returns any type of object
  var numbers = [
  [1, 2, 3],
  [4, 5, 6],
  [-7, -6, -5],
 ];
  console.log(numbers.pop()); // [ -7, -6, -5]
  console.log(numbers); // [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

Output

 [ 'JavaScript', 'Python', 'Java', 'C++' ]
 Lua
[ -7, -6, -5]
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

Array push()

With the aid of examples, we will learn about the JavaScript Array push() method in this article.

The array's end is expanded by the push() method by zero or more elements. Example

 let city = ["New York", "Chicago", "Madrid"];

 // add "London" to the array
 city.push("London");

 console.log(city);

// Output: [ 'New York', 'Chicago', 'Madrid', 'London' ]

push() Syntax The syntax of the push() method is:

arr.push(element1, element2, ..., elementN)

Here, arr is an array.

push() Parameters

  • The array can have any number of elements added to it using the push() method. push() Return Value

  • Returns the array's new length, which is the length of the array after the method's parameters have been added.

Notes:

  • This method changes the original array and its length.
  • To add elements to the beginning of an array, use the JavaScript Array unshift() method.

Example: Using push() method

var languages = ["JavaScript", "Python", "Java", "Lua"];

var count = languages.push("C++");
console.log(languages); // [ 'JavaScript', 'Python', 'Java', 'Lua', 'C++' ]
console.log(count); // 5

var priceList = [12, 21, 35];

var count1 = priceList.push(44, 10, 1.6);
console.log(priceList); // [ 12, 21, 35, 44, 10, 1.6 ]
console.log(count1); // 6

Output

[ 'JavaScript', 'Python', 'Java', 'Lua', 'C++' ]
5
[ 12, 21, 35, 44, 10, 1.6 ]
6

Array Unshift()

With the help of examples, we will learn about the JavaScript Array shift() method in this lesson.

The unshift() method increases the length of an array by one or more elements and returns the original array length. Example

   let languages = ['Java', 'Python', 'C#'];

  // add'JavaScript' at the beginning of the array
  languages.unshift('JavaScript');
  console.log(languages);

 // Output: [ 'JavaScript', 'Java', 'Python', 'C#' ]

unshift() Syntax The syntax of the unshift() method is:

  arr.unshift(element1, element2, ..., elementN)

Here, arr is an array.

unshift() Parameters

The unshift() method takes in an arbitrary number of elements to add to the array.

unshift() Return Value

  • returns the length of the array that the method was called on after adding arguments to the beginning of the array.

Notes:

  • This method changes the original array and its length. Use the JavaScript Array push() method to add items to the end of an array.

Example: Using unshift() method

 var languages = ['JavaScript', 'Python', 'Java', 'C#'];

 var count = languages.unshift('C++');
 console.log(languages); // [ 'C++', 'JavaScript', 'Python', 'Java', 'C#' ]
 console.log(count); // 5

 var priceList = [12, 25, 40];

 var count1 = priceList.unshift(50, 10, 1.8);
 console.log(priceList); // [ 50, 10, 1.8, 12, 25, 40 ]
 console.log(count1); // 6

Output

[ 'C++', 'JavaScript', 'Python', 'Java', 'C#' ]
5
[ 50, 10, 1.8, 12, 25, 40 ]
6

Array splice()

With the help of examples, we will learn about the JavaScript String splice() technique in this article.

After altering (adding/removing) an array's elements in place, the splice() method returns an array.

Example

  let prime_numbers = [2, 3, 5, 7, 9, 11];

  // replace 1 element from index 4 by 13
  let removedElement = prime_numbers.splice(4, 1, 13);
  console.log(removedElement);
  console.log(prime_numbers);

  // Output: [ 9 ]
 //         [ 2, 3, 5, 7, 13, 11 ]

spice() Syntax The syntax of the splice() method is:

 arr.splice(start, deleteCount, item1, ..., itemN)

Here, arr is an array.

splice() Parameters

The splice() method takes in:

  • start - The index from where the array is changed.
  • deleteCount (optional) - The number of items to remove from start.
  • item1, ..., itemN (optional) - The elements to add to the start index. If not specified, splice() will only remove elements from the array.

splice() Return Value

  • Returns an array containing the deleted elements.

Note: The splice() method changes the original array.

Example 1: Using splice() method

let languages = ['JavaScript', 'Python', 'Java', 'Lua'];

// replacing 'Java' & 'Lua' with 'C#' & 'C++'
let removed = languages.splice(2, 2, 'C#', 'C++');
console.log(removed); // [ 'Java', 'Lua' ]
console.log(languages); // [ 'JavaScript', 'Python', 'C', 'C++' ]

// adding elements without deleting existing elements
let removed1 = languages.splice(1, 0, 'Java', 'Lua');
console.log(removed1); // []
console.log(languages); // [ 'JavaScript', 'Java', 'Lua', 'Python', 'C', 'C++' ]

// removing 3 elements
let removed2 = languages.splice(2, 3);
console.log(removed2); // [ 'Lua', 'Python', 'C' ]
console.log(languages); // [ 'JavaScript', 'Java', 'C++' ]

Output

[ 'Java', 'Lua' ]
[ 'JavaScript', 'Python', 'C', 'C++' ]
[]
[ 'JavaScript', 'Java', 'Lua', 'Python', 'C', 'C++' ]
[ 'Lua', 'Python', 'C' ]
[ 'JavaScript', 'Java', 'C++' ]

Example 2: Using splice() for different deleteCount values

  • If start > array.length, splice() does not delete anything and starts appending arguments to the end of the array.
  • If start < 0, the index is counted from backward (array.length + start). For example, -1 is the last element.
  • If array.length + start < 0, it will begin from index 0.

    let languages = ['JavaScript', 'Python', 'Java', 'Lua'];
    
    // does not removes, only appends to the end
    let removed = languages.splice(8, 4, 'C++');
    console.log(removed); // []
    console.log(languages); // ['JavaScript', 'Python', 'Java', 'Lua', 'C++']
    
    // remove last element and add 3 more elements
    let removed1 = languages.splice(-1, 1, 'Swift', 'Scala', 'Go');
    console.log(removed1); // [ 'C++' ]
    console.log(languages); // ['JavaScript', 'Python', 'Java', 'Lua', 'Swift', 'Scala', 'Go']
    

Output

  []
  ["JavaScript", "Python", "Java", "Lua", "C++"]
  [ 'C++' ]
  ["JavaScript", "Python", "Java", "Lua", "Swift", "Scala", "Go"]

Example 3: Using splice() for different start values

  • The array's whole contents are deleted if deleteCount is omitted or is more than the number of remaining elements.
  • No elements are erased if deleteCount is zero or negative. However, at least one new element needs to be mentioned.

     let languages = ["JavaScript", "Python", "Java", "C#"];
    
     // removes everything from start
     let removed = languages.splice(1);
     console.log(removed); // [ "Python", "Java", "C#" ]
     console.log(languages); // [ "JavaScript" ]
    
     // remove none & add 3 more element
     let removed1 = languages.splice(1, -2, "Swift", "Scala", "Go");
     console.log(removed1); // [ ]
     console.log(languages); // [ "JavaScript", "Swift", "Scala", "Go" ]
    

Output

    [ "Python", "Java", "C#" ]
    [ "JavaScript" ]
    [ ]
    ["JavaScript", "Swift", "Scala", "Go"]

You can study more on Array Methods here.

Conclusion

In this article, we learned how to use JavaScript's Array Methods to organize our Array Data Structure. This has benefits including testability and portability.

This method does, however, sacrifice further degrees of abstraction, which some might consider superfluous given the scope of its use. I have discovered that there is a greater demand for structure the larger the application. Knowing how big that is is the tricky part, and it is surprisingly simple to exceed that size.