JavaScript Array and the methods

JavaScript Array and the methods

Arrays are collections of items. They can be used to store multiple items of different types in one variable. Each item in the array is called an element. An array can contain elements of different data types like numbers, strings, objects, and more arrays.

One crucial benefit of arrays is that you can loop through the elements of an array. You can also access any element of the array and change it if you want.

In this article, you'll learn about:

  • Arrays and how to create an array
  • Array indexes
  • How to access elements of an array
  • How to add and remove elements from an array
  • Getting the length of an array
  • Some array methods like sort(), slice(), join(), map() and many more.

How to create an array

You can create an array in javascript in two ways:

1. Array literal

In this method, the elements are enclosed in square brackets. The elements are separated by a comma. Check out this example:

const myArray = ["orange", 3, True]

2. The Array() constructor

You can also create an array using the new keyword.

const myArray = new Array("car", "houses", "fruits")

The most popular and simplest method of creating an array is the first method(array literal).

Array indexes

An index refers to the position of a particular element in an array. In javascript, indexes start from 0. This means that the first element in the array has an index of 0, the second element has an index of 1, and so on.

const animals = ["cat", "dog", "lion", "goat"]
// The first element, cat, has an index of 0.
// The last element, goat, has an index of 3.

Accessing the elements of an array

One use of indexes is that they let you access array elements. The syntax goes like this:

array_name[index number]

See the example below

const names = ["John", "Martha", "Tyler", "Jessy"];
console.log(names[2]);
// Tyler

You can change the elements of an array. This shows that arrays are mutable.

const names = ["John", "Martha", "Tyler", "Jessy"];
names[1] = "Stella"
console.log(names)
// ["John", "Stella", "Tyler", "Jessy"]

From the above example, you can see that the name Stella replaced Martha.

How to add and remove elements from a JavaScript array

The push() method is used to add elements to the end of an array.

const animals = ["cat", "dog", "lion", "goat"];
animals.push("deer");
console.log(animals);
// ["cat", "dog", "lion", "goat", "deer"]

The unshift() method is used to add elements to the beginning of an array.

const animals = ["cat", "dog", "lion", "goat"];
animals.unshift("elephant");
console.log(animals);
// ["elephant", "cat", "dog", "lion", "goat"]

The pop() method is used to remove elements from the end of an array.

const animals = ["cat", "dog", "lion", "goat"];
const removedElement = animals.pop();
console.log(animals);
// ["cat", "dog", "lion"]

console.log(removedElement);
// goat

The shift() method is used to remove elements from the beginning of an array

const animals = ["cat", "dog", "lion", "goat"];
const addedElement = animals.shift();
console.log(animals);
// ["dog", "lion", "goat]
console.log(addedElement);
// cat

You can also create an empty array and add elements to it like this:

const animals = [ ];
animals[0] = "cat";
animals[1] = "dog";
animals[2] = "lion";
console.log(animals);
// ["cat", "dog", "lion"]

How to get the length of an array

The length of an array means the amount of elements contained in that array. This can be gotten by the length property.

const animals = ["cat", "dog", "lion", "goat"];
console.log(animals.length);
// 4

The array length is always one number more than the highest index of the array. From the above example, the highest index is 3 but the length of the array is 4.

Array Methods

Methods are the most exciting thing about arrays. You can do so much with the data you store in arrays using array methods. You can manipulate the elements in the arrays how you want. You have already learnt about some of the methods like push(), unshift(), pop(), shift(). Let us take a look at some more methods.

The sort() method

This method arranges elements of an array in alphabetical order.

const animals = ["dog", "lion", "goat", "cat"]
console.log(animals.sort())
// ["cat", "dog", "goat", "lion"]

The sort() method regards elements as strings. It brings "cat" before "dog". However, using it with numbers may produce an incorrect result. The sort() method would put 110 before 27 because 1 is less that 2. In order to correct this, a comparator function is introduced like this:

const numbers = [10, 5, 26, 3, 18, 31];
numbers.sort(function(a, b) { return a - b});
// [3, 5, 10, 18, 26, 31]

The slice() method

The slice method is used to make a new copy of an array. The original array is not tampered with; rather another array is created that is identical to the original array.

const names = ["John", "Martha", "Tyler", "Jessy"];
const clonedNames = names.slice();
console.log(clonedNames);
// ["John", "Martha", "Tyler", "Jessy"]

The spread operator

The spread operator is represented by three dots(...). It is also used to create a copy of an array

const names = ["John", "Martha", "Tyler", "Jessy"];
const clonedNames =[...names];
console.log(clonedNames);
// ["John", "Martha", "Tyler", "Jessy"]

The join() method

This method joins the elements of an array, seperates by them by a "seperator", and then returns a string. The comma(,) is the default seperator, however, you can specify the seperator you want

const names = ["John", "Martha", "Tyler", "Jessy"];
console.log(names.join());
// "John, Martha, Tyler, Jessy"

//You can specify the seperator you want
const names = ["John", "Martha", "Tyler", "Jessy"];
console.log(names.join(-));
// "John-Martha-Tyler-Jessy"

The Map() method

The Map() method iterates over an array and performs tasks on each element depending on a callback function. It does not affect the original array; rather it returns a new array.

const numbers = [2, 3, 4, 5, 6];

// Let's assume we want to add 10 to each element in the numbers array

const mapNumbers = numbers.map(function(item) {return item + 10;});
console.log(mapNumbers);
// [12, 13, 14, 15, 16]
// This is can be made easier using an arrow function

const mapNumbers = number.map(item => item + 10);
// [12, 13, 14, 15, 16]

The filter() method

This method iterates over the array, and returns a new array containing the elements that fullfil the condition specified in a callback function

// Let's try to pick out those numbers that are divisible by 2(no remainders)

const numbers = [2, 3, 4, 5, 6];
const divisible = numbers.filter( num => num % 2 == 0);
console.log(divisible);
// [2, 4, 6]

The concat method

This method combines two or more arrays.

const array1 = ["apple", "orange"];
const array2 = ["banana", "pear"];
const array3 = ["mango", "pineapple"];

const combined = array1.concat(array2); 
console.log(combined);
// ["apple", "orange", "banana", "pear"]

const combineAll =array1.concat(array2, array3);
console.log(combineAll);
// ["apple", "orange", "banana", "pear", "mango", "pineapple"]

Conclusion

It is obvious that arrays are crucial in javascript. The possibilities are so much with arrays. You can store and manipulate data anyhow you want. Some important array methods were talked about here, but there are many more to explore. Thanks for reading.