JavaScript : All About Arrays

JavaScript : All About Arrays

ยท

6 min read

An array is a special variable, which can hold more than one value and of various data types, unlike the majority of other languages which can hold only similar types of values.

const array = ['Ariana', 30.5, false, 'Pete'];

They are probably the most used data structure in JavaScript, hence it has countless array methods. In this blog, we will learn these methods and also understand when to use which method.

Simple Array Methods

First of all, let's understand how can we call methods on objects. Methods are functions attached to objects. If we have array methods that means arrays themselves are objects.

Push

The push method adds an element at the end of an array. It returns a new array length.

const hogwarts = ['Harry', 'Hermione', 'Ron'];
const newTeam = hogworts.push('Luna');\
console.log(newTeam); // 4
console.log(hogwarts); // [ Harry, Hermione, Ron, Luna ]

Pop

The pop method removes an element from the end of an array and we can store the removed element in a variable.

const hogwarts = ['Harry', 'Hermione', 'Ron', 'Luna'];
const expelled = hogworts.pop();
console.log(expelled); // Luna
console.log(hogwarts); // [ Harry, Hermione, Ron]

Shift

The shift method removes the first array element and "shifts" all other elements to a lower index and can store the removed element in a variable.

const hogwarts = ['Harry', 'Hermione', 'Ron'];
const expelled = hogwarts.shift();
console.log(expelled); // Harry
console.log(hogwarts); // [ Hermione, Ron]

Unshift

The unshift method adds a new element to an array at the beginning and "unshifts" older elements. It returns the new array length.

const hogwarts = ['Harry', 'Hermione', 'Ron'];
const newTeam = hogwarts.unshift('Dumbledore');
console.log(newTeam); // 3
console.log(hogwarts); // [ Dumbledore, Harry, Hermione, Ron]

Length

The length method - quite obvious, returns the length of the array.

const hogwarts = ['Harry', 'Hermione', 'Ron', 'Luna', 'Draco'];
const hogwartsClass = hogwarts.length();
console.log(hogwartsClass); // 5

toString

The toString method converts an array to a string of (comma-separated) array values.

const hogwarts = ['Harry', 'Hermione', 'Ron', 'Luna', 'Draco'];
const listOfStudents = hogwarts.toString();
console.log(listOfStudents); // Harry, Hermione, Ron, Luna, Draco

Concat

The concat method creates a new array by merging existing arrays. It can take any number of array arguments.

const wizards = ['Harry', 'Ron', 'Draco'];
const witches = ['Hermione', 'Ginny', 'Luna'];
const professors = ['Snape', 'Lupin', 'Trelawney'];

const hogwarts = professors.concat(wizards, witches);
console.log(hogwarts);
// [ Snape, Lupin, Trelawney, Harry, Ron, Draco, Hermione, Ginny, Luna]

Slice

The slice method slices out a piece of an array into a new array.

If only one argument is given, it returns an array from the given index to the last element. If two arguments are given The method then selects elements from the start argument, and up to (but not including) the end argument.

// For one argument
const teamPartialVoldy = ['Snape', 'Bellatrix', 'Barty', 'Lucius'];
const deathEaters = teamPartialVoldy.slice(1);
console.log(deathEaters); // [ Bellatrix, Barty, Lucius];

// For two arguments
const teamRandom = ['Snape', 'Bellatrix', 'Lucius', 'Dumbledore'];
const deathEaters = teamPartialVoldy.slice(1, 3);
console.log(deathEaters); // [ Bellatrix, Lucius];

Splice

The splice method can be used to add or remove elements from an array.

Adding elements

const hogwartsHouse = ['Gryffindor', 'Hufflepuff', 'Slytherin'];
hogwartsHouse.splice(2, 0, 'Ravenclaw');
console.log(hogwartsHouse); // [Gryffindor, Hufflepuf, Ravenclaw, Slytherin]

The first parameter (2) defines the position where new elements should be added.

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Ravenclaw") define the new elements to be added.

Removing elements

With clever parameter settings, you can use splice to remove elements without leaving holes in the array.

const hogwartsHouse = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'];
hogwartsHouse.splice(3, 1,);
console.log(hogwartsHouse); // [Gryffindor, Hufflepuf, Ravenclaw ]

The first parameter (3) defines the position where new elements should be added.

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

Includes

The includes method checks if the array contains a particular element and returns a boolean value.

const hogwartsHouse = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'];
const smartPants = hogwartsHouse.includes('Ravenclaw');
console.log(smartPants); // true

Join

The join method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).

const hogwartsHouse = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'];
const listOfHouses = hogwartsHouse.join(' ');
console.log(listOfHouses); // Gryffindor Hufflepuff Ravenclaw Slytherin

Looping Arrays: forEach

The forEach method calls a function for each element in an array.

Syntax:

array.forEach(function(currentValue, index, arr), thisValue);

Here, index and arr passing is optional.

For example:

const harry = ['H', 'a', 'r', 'r', 'y'];
let harryName = ' ';

function joinName(currentLetter){
    harryName = harryName + currentLetter;
};

harry.forEach(joinName);
console.log(harryName); // Harry

To see how all arguments are used. Let's see another example

const numbers = [10, 30, 50, 70];
numbers.forEach(myFunction);

function myFunction(item, index, arr) {
  arr[index] = item * 10;
}

console.log(numbers); // [100, 300, 500, 700]

Data Transformations

Map

The map method creates a new array by calling a function for every array element. It calls a function once for each element in an array.

Syntax:

array.map(function(currentValue, index, arr), thisValue)

For Example:

const students = [
  {firstname : "Harry", lastname: "Potter"},
  {firstname : "Hermione", lastname: "Granger"},
  {firstname : "Ronald", lastname: "Weasley"}
];

students.map(getFullName);

function getFullName(item) {
  return [item.firstname,item.lastname].join(" ");
} 
// Harry Potter
// Hermione Granger
// Ronald Weasley

Here, an array containing names and surnames is created. To map the array, a function is passed which joins name and surname to create full name of the student.

Filter

The filter method creates a new array filled with elements that pass a test provided by a function.

Syntax:

array.filter(function(currentValue, index, arr), thisValue)

For example:

const Harry = {
  name: "Harry",
  house: "Gryffindor",
};
const Ron = {
  name: "Ron",
  house: "Gryffindor",
};
const Draco = {
  name: "Draco",
  house: "Slytherin",
};
const Luna = {
  name: "Luna",
  house: "Ravenclaw",
};

const students = [Harry, Ron, Draco, Luna];

function gryffindorClub(name) {
  return name.house === "Gryffindor";
}

const gClub = students.filter(gryffindorClub);
console.log(gClub);
// [ { name: 'Harry',house: 'Gryffindor' },
//   { name: 'Ron',house: 'Gryffindor' } ]

Here, four objects (Harry, Ron, Draco and Luna) are made, containing their name and house. A function is made which returns the object having house Gryffindor. To apply the filter method, this function is passed.

Reduce

The reduce method executes a reducer function for the array element. It returns a single value - the function's accumulated result.

Syntax:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

For example:

const gryffPoints = [200, -50, 100, 50, -250];

function getTotalPoints(total, num) {
  return total + num;
}

const totalPoints = numbers.reduce(getTotalPoints, 0);

console.log(totalPoints); // 50

Here, an array of points of Gryffindor's house is created. A function is created which adds all the points. This function is passed to the reduce method.

Other methods

Find

The find method returns the value of the first element that passes a test. It executes a function for each array element.

Syntax:

array.find(function(currentValue, index, arr),thisValue)

For example:

const housePoints = [190, 260, 180, 240];

function checkPoints(point) {
  return point > 250;
}

const highestPoints = housePoints.find(checkPoints);
console.log(highestPoints); // 260

findIndex

The findIndex method executes a function for each array element. It returns the index (position) of the first element that passes a test.

Syntax:

array.findIndex(function(currentValue, index, arr),thisValue)

For example:

const housePoints = [190, 260, 180, 240];

function checkPoints(point) {
  return point > 250;
}

const highestPoints = housePoints.findIndex(checkPoints);
console.log(highestPoints); // 1

Hope this blog enhanced your knowledge about array methods. ๐Ÿ˜„

ย