JavaScript Array Handbook

JavaScript Array Handbook

·

9 min read

In programming, an array is a collection of elements or items. Arrays store data as elements and retrieve them back when you need them.

What is an Array in JavaScript?

A pair of square brackets [] represents an array in JavaScript. All the elements in the array are comma(,) separated.

In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays.

Declaration of an Array

There are basically two ways to declare an array.

Example:

var House = [ ]; // method 1 
var House = new Array(); // method 2

Example (for Method 1):

// Initializing while declaring
var sports= ["Football", "Cricket", "Basketball", "Volleyball"];

Example (for Method 2):

// Initializing while declaring
// Creates an array having elements 10, 20, 30, 40, 50
var house = new Array(10, 20, 30, 40, 50);

//Creates an array of 5 undefined elements
var house1 = new Array(5);

//Creates an array with element 1BHK
var home = new Array("1BHK");

An array in JavaScript can hold different elements.

We can store Numbers, Strings and Boolean in a single array.

For an instance:

// Storing number, boolean, strings in an Array
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];

Accessing Array Elements.

Array in JavaScript are indexed from 0 so we can access array elements as follows:

var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
alert(house[0]+" cost= "+ house[1]);
var cost_1BHK = house[1];
var is_for_rent = house[5];
alert("Cost of 1BHK = "+ cost_1BHK);
alert("Is house for rent = ")+ is_for_rent);

Length property of an Array.

Length property of an Array returns the length of an Array. Length of an Array is always one more than the highest index of an Array.

var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];

//len contains the length of the array
var len = house.length;
for (var i = 0; i < len; i++)
    alert(house[i]);

JavaScript Basic Array Methods

  • Array.push() : Adding Element at the end of an Array. As array in JavaScript are mutable object, we can easily add or remove elements from the Array. And it dynamically changes as we modify the elements from the array.

Syntax:

Array.push(item1, item2 …)
Parameters: Items to be added to an array.
// Adding elements at the end of an array
// Declaring and initializing arrays
var number_arr = [ 10, 20, 30, 40, 50 ];
var string_arr = [ "London", "Liverpool", "Birmingham", "Edinburgh" ];

// push()
// number_arr contains [10, 20, 30, 40, 50, 60]
number_arr.push(60);

// We can pass multiple parameters to the push()
// number_arr contains
// [10, 20, 30, 40, 50, 60, 70, 80, 90]
number_arr.push(70, 80, 90);

// string_arr contains
// ["London", "Liverpool", "Birmingham, "Edinburgh", "Oxford", "Belfast"]
string_arr.push("Oxford", "Belfast");

// Printing both the array after performing push operation
console.log("After push op " + number_arr);
console.log("After push op " + string_arr);

Array Push.png

  • Array.unshift() : Adding elements at the front of an Array.

Syntax:

Array.unshift(item1, item2 …)
Parameters: Items to be added to the array
// Adding element at the beginning of an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40 ];
var string_arr = [ "London", "Birmingham" ];

// unshift()
// number_arr contains
// [10, 20, 20, 30, 40]
number_arr.unshift(10, 20);

// string_arr contains
// ["Oxford", "Derby", "London", "Derby"]
string_arr.unshift("Oxford", "Derby");

// Printing both the array after performing unshift operation
console.log("After unshift op " + number_arr);
console.log("After unshift op " + string_arr);

Array unshift.png

  • Array.pop() : Removing elements from the end of an array.

Syntax:

Array.pop()
Parameters: It takes no parameter
// Removing elements from the end of an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50 ];
var string_arr = [ "London", "Birmingham", "Derby" ];

// pop()
// number_arr contains
// [ 20, 30, 40 ]
number_arr.pop();

// string_arr contains
// ["London", "Birmingham"]
string_arr.pop();

// Printing both the array after performing pop operation
console.log("After pop op " + number_arr);
console.log("After popo op " + string_arr);

Array Pop.png

  • Array.shift() : Removing elements at the beginning of an array.

Syntax:

Array.shift()
Parameter : it takes no parameter
// Removing element from the beginning of an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50, 60 ];
var string_arr = [ "London", "Birmingham", "Derby", "Chester" ];

// shift()
// number_arr contains
//  [30, 40, 50, 60];
number_arr.shift();

// string_arr contains
// ["Birmingham", "Derby", "Chester"]
string_arr.shift();

// Printing both the array after performing shifts operation
console.log("After shift op " + number_arr);
console.log("After shift op " + string_arr);

Array Shift.png

  • Array.splice() : Insertion and Removal in between an Array.

Syntax:

Array.splice (start, deleteCount, item 1, item 2….) 
Parameters:  
Start : Location at which to perform operation
deleteCount: Number of element to be deleted, 
if no element is to be deleted pass 0.
Item1, item2 …..- this is an optional parameter . 
These are the elements to be inserted from location start
// Removing an adding element at a particular location
// in an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50, 60 ];
var string_arr = [ "amit", "sumit", "anil", "prateek" ];

// splice()
// deletes 3 elements starting from 1
// number array contains [20, 60]
number_arr.splice(1, 3);

// doesn't delete but inserts 3, 4, 5
// at starting location 1
number_arr.splice(1, 0, 3, 4, 5);

// deletes two elements starting from index 1
// and add three elements.
// It contains  ["amit", "xyz", "geek 1", "geek 2", "prateek"];
string_arr.splice(1, 2, "xyz", "geek 1", "geek 2");

// Printing both the array after performing splice operation
console.log("After splice op " + number_arr);
console.log("After splice op " + string_arr);

Array Splice.png

JavaScript Array sort() Method

The arr.sort() method is used to sort the array in place in a given order according to the compare() function. If the method is omitted then the array is sorted in ascending order.

Syntax:

arr.sort(compareFunction)
<script>
// JavaScript to illustrate sort() function
function func() {

    // Original string
    var arr = ["Learn", "Code", "Online"]

    document.write(arr);
    document.write("<br>");
    // Sorting the array
    document.write(arr.sort());
}
func();
</script>

Output :

Learn,Code,Online
Learn,Online,Code

Parameters: This method accept a single parameter as mentioned above and described below:

  • compareFunction: This parameters is used to sort the elements according to different attributes and in the different order.
  • compareFunction(a,b) < 0
  • compareFunction(a,b) > 0
  • compareFunction(a,b) = 0

  • Return value: This method returns the reference of the sorted original array. Below examples illustrate the JavaScript Array sort() method:

Example : In this example the sort() method arranges the elements of the array in ascending order.

var arr = [2, 5, 8, 1, 4]
document.write(arr.sort());
document.write(arr);

Output:

1,2,4,5,8
1,2,4,5,8

How to select a random element from array in JavaScript ?

In order to select random element from array in JavaScript we can use below method.

  • Use Math.random() function to get the random number between(0-1, 1 exclusive).
  • Multiply it by the array length to get the numbers between(0-arrayLength).
  • Use Math.floor() to get the index ranging from(0 to arrayLength-1).

Example:

How to Create, Remove, Update, and Access Arrays in JavaScript

Here, we will learn about methods we can use to create a new array, remove elements to make the array empty, access elements, and many more.

  • The concat() array method.

The concat() method merges one or more arrays and returns a merged array. It is an immutable method. This means it doesn't change (mutate) existing arrays.

Let's concat two arrays.

const first = [1, 2, 3];
const second = [4, 5, 6];

const merged = first.concat(second);

console.log(merged); // [1, 2, 3, 4, 5, 6]
console.log(first); // [1, 2, 3]
console.log(second); // [4, 5, 6]

Using the concat() method we can merge more than two arrays. We can merge any number of arrays with this syntax:

array.concat(arr1, arr2,..,..,..,arrN);

Example:

const first = [1, 2, 3];
const second = [4, 5, 6];
const third = [7, 8, 9];

const merged = first.concat(second, third);

console.log(merged); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • The join() array method.

The join() method joins all the elements of the array using a separator and returns a string. The default separator used for joining is comma(,).

const WebDev = ["HTML", "CSS", "Tailwinnd CSS", "JavaScript"];
document.getElementById("demo").innerHTML = WebDev.join(" * ");

Output:

HTML*CSS*Tailwinnd CSS*JavaScript
  • The includes() array method. You can determine the presence on an element in an array using the includes() method. If the element is found, the method returns true, and falseotherwise.
const places = ['Birmingham', 'Derby', 'Vienna', 'Texas'];

places.includes('Texas'); // returns true
places.includes('july'); // returns false
  • The indexOf() array method.

You may want to know the index position of an element in array. You can use the indexOf()method to get that. It returns the index of the first occurrence of an element in the array. If an element is not found, the indexOf() method returns -1.

const places = ['Birmingham', 'Derby', 'Vienna', 'Texas'];

places.indexOf('Derby'); // returns 1
places.indexOf('Edinburgh'); // returns -1
  • The reverse() array method.

As the name itself suggests, the reverse() method reverses the elements' positions in the array so that the last element goes into the first position and the first one to the last.

const places = ['Derby', 'Vienna', 'Texas'];

places.reverse(); // returns ["Texas", "Vienna", "Derby"]
  • The some() array method.

The some() method returns a boolean value (true/false) based on at least one element in the array passing the condition in the function. Let's see if there are any students below the age 30.

let hasStudentBelow30 = students.some((element, index) => {
  return element.age < 30;
});

console.log(hasStudentBelow30); // true

Before We End...

I hope you've found this article insightful, and that it helps you understand JavaScript arrays more clearly.

Let's connect. You will find me active on LinkedIn , Instagram and FindCoder.io.

You may also like these articles:

Did you find this article valuable?

Support Anand by becoming a sponsor. Any amount is appreciated!