JS Array Methods Explained with Examples

sangeethpsk

sangeethpsk

Posted on May 5, 2022

JS Array Methods Explained with Examples

what is an array in javascript

A pair of square brackets [] represents an array in JavaScript. All the elements 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.

Here is an example of an array with four elements: type Number, Boolean, String, and Object.

const mixedTypedArray = [100, true, 'Hello', {}];
Enter fullscreen mode Exit fullscreen mode

The position of an element in the array is known as its index. In JavaScript, the array index starts with 0, and it increases by one with each element.

So, for example, in the above array, the element 100 is at index 0, true is at index 1, 'Hello' is at index 2, and so on.

The number of elements in the array determines its length. For example, the length of the above array is four.

How to Create an Array in JavaScript

You can create an array in multiple ways in JavaScript. The most common way is by assigning an array value to a variable.

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
Enter fullscreen mode Exit fullscreen mode

You can also use array constructor to create an array

const salad = new Array('πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘');
Enter fullscreen mode Exit fullscreen mode

How to Get Elements from an Array

You can access elements from array using its index.
you need square bracket syntax to access array elements

const element = array[index];
Enter fullscreen mode Exit fullscreen mode

When you're accessing elements using index like this:

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
salad[0]; // 'πŸ…'
salad[2]; // 'πŸ₯¦'
salad[5]; // 'πŸ₯•'
Enter fullscreen mode Exit fullscreen mode

You can use the length of an array to traverse backward and access elements.

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
const len = salad.length;
salad[len - 1]; // 'πŸ₯‘'
salad[len - 3]; // '🌽'
Enter fullscreen mode Exit fullscreen mode

you can also loop through the array using regular for or forEach or any other loop

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];

for(let i=0; i<salad.length; i++) {
  console.log(`Element at index ${i} is ${salad[i]}`);
}
Enter fullscreen mode Exit fullscreen mode

How to Add Elements to an Array

Use push method to insert an element into an array. The push method add element at the end of the array

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
salad.push('πŸ₯œ');
Enter fullscreen mode Exit fullscreen mode

Now the salad array is:

["πŸ…", "πŸ„", "πŸ₯¦", "πŸ₯’", "🌽", "πŸ₯•", "πŸ₯‘", "πŸ₯œ"]

if you want to add an element to the beginning of the array, you'll need to use unshift() method

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
salad.unshift('πŸ₯œ');
Enter fullscreen mode Exit fullscreen mode

Now the salad array is:

["πŸ₯œ", "πŸ…", "πŸ„", "πŸ₯¦", "πŸ₯’", "🌽", "πŸ₯•", "πŸ₯‘"]

How to Remove Elements from an Array

the easiest way to remove a single element from an array is using pop() method.Every time you call the pop() method, it removes an element from the end of array.

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
salad.pop(); // πŸ₯‘

console.log(salad); // ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•']
Enter fullscreen mode Exit fullscreen mode

Use the shift() method to remove an element from the beginning of an array

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
salad.shift(); // πŸ…

console.log(salad); // ['πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
Enter fullscreen mode Exit fullscreen mode

How to Copy and Clone an Array

You can copy and clone an array to new array using slice() method
Note that slice method doesn't change the original array, it create a new shallow copy of that original array

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];
const saladCopy = salad.slice();

console.log(saladCopy); // ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘']

salad === saladCopy; // returns false
Enter fullscreen mode Exit fullscreen mode

How to Determine if a Value is an Array

You can determine if value is an array using Array.isArray(value) method .This method return true if the passed value is an array.

Array Destructuring in JavaScript

We have some new syntax to extract multiple properties from an array

Here is an example:

let [tomato, mushroom, carrot] = ['πŸ…', 'πŸ„', 'πŸ₯•'];

console.log(tomato, mushroom, carrot); // Output, πŸ… πŸ„ πŸ₯•
Enter fullscreen mode Exit fullscreen mode

To do the same thing without the destructuring, it would look like this:

let vegetables = ['πŸ…', 'πŸ„', 'πŸ₯•'];
let tomato = vegetables[0];
let mushroom= vegetables[1];
let carrot= vegetables[2];
Enter fullscreen mode Exit fullscreen mode

How to Assign a Default Value to a Variable

You can assign a default value using destructuring when there is no value or undefined for the array element.

let [tomato , mushroom = 'πŸ„'] = ['πŸ…'];
console.log(tomato); // 'πŸ…'
console.log(mushroom ); // 'πŸ„'
Enter fullscreen mode Exit fullscreen mode

How to Skip a Value in an Array

In the example below, we skip the mushroom element. Notice the space in the variable declaration at the left side of the expression.

let [tomato, , carrot] = ['πŸ…', 'πŸ„', 'πŸ₯•'];

console.log(tomato); // 'πŸ…'
console.log(carrot); // 'πŸ₯•'
Enter fullscreen mode Exit fullscreen mode

Nested Array Destructuring

In javascript arrays can be nested.This means that an array can have another array as an element.

For example, let's create a nested array for fruits. It has a few fruits and an array of vegetables in it.

let fruits = ['🍈', '🍍', '🍌', 'πŸ‰', ['πŸ…', 'πŸ„', 'πŸ₯•']];
Enter fullscreen mode Exit fullscreen mode

How would you access the 'πŸ₯•' from the above array? Again, you could do this without destructuring, like this:

const veg = fruits[4]; // returns the array ['πŸ…', 'πŸ„', 'πŸ₯•']
const carrot = veg[2]; // returns 'πŸ₯•'
Enter fullscreen mode Exit fullscreen mode

Alternatively, you could use this short-hand syntax:

fruits[4][2]; // returns 'πŸ₯•'
Enter fullscreen mode Exit fullscreen mode

You can also access it using the destructuring syntax, like this:

let [,,,,[,,carrot]] = ['🍈', '🍍', '🍌', 'πŸ‰', ['πŸ…', 'πŸ„', 'πŸ₯•']];
Enter fullscreen mode Exit fullscreen mode

How to Use the Spread Syntax and Rest Parameter

Since ES6, we can use the ... (three consecutive dots) as spread syntax and the rest parameter in array destructuring.

For the rest parameter, the ... appears on the left side of the destructuring syntax.

For the spread syntax, the ... appears on the right side of the destructuring syntax.

How to Use the Rest Parameter in JS

We can map out the left elements of an array in a new array.
The rest parameter must be the last variable in destructuring
syntax

In the example below, we have mapped the first two of the array elements to the tomato and mushroom variables. The remaining elements are mapped to the rest variable using the .... The rest variable is a new array containing the leftover elements.

const [tomato, mushroom, ...rest] = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];

console.log(tomato); // 'πŸ…'
console.log(mushroom); // 'πŸ„'
console.log(rest); // ["πŸ₯¦", "πŸ₯’", "🌽", "πŸ₯•", "πŸ₯‘"]
Enter fullscreen mode Exit fullscreen mode

How to Use the Spread Operator in JS

With the spread operator, we can create a clone/copy of an existing array like this:

const salad = ['πŸ…', 'πŸ„', 'πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘'];

const saladCloned = [...salad];
console.log(saladCloned); // ["πŸ…", "πŸ„", "πŸ₯¦", "πŸ₯’", "🌽", "πŸ₯•", "πŸ₯‘"]

salad === saladCloned // false
Enter fullscreen mode Exit fullscreen mode

How to Swap Values with Destructuring

We can swap the value of two variables easily using the array destructuring syntax.

let first = 'πŸ˜”';
let second = 'πŸ™‚';
[first, second] = [second, first];

console.log(first);  // 'πŸ™‚'
console.log(second); // 'πŸ˜”'
Enter fullscreen mode Exit fullscreen mode

Merge Arrays

We can merge two arrays and create a new array with all elements from both arrays. let's take two arrays

const emotion = ['πŸ™‚', 'πŸ˜”'];
const veggies = ['πŸ₯¦', 'πŸ₯’', '🌽', 'πŸ₯•'];
Enter fullscreen mode Exit fullscreen mode

Now, we will merge them to create a new array.

const emotionalVeggies = [...emotion, ...veggies];
console.log(emotionalVeggies); // ["πŸ™‚", "πŸ˜”", "πŸ₯¦", "πŸ₯’", "🌽", "πŸ₯•"]
Enter fullscreen mode Exit fullscreen mode

JavaScript Array Methods

We have seen few array methods and properties

  1. push() – Insert an element at the end of the array
  2. unshift() – Insert an element at the beginning of the array.
  3. pop() – Remove an element from the end of the array.
  4. shift() – Remove an element from the beginning of the array.
  5. slice() – Create a shallow copy of an array.
  6. Array.isArray() – Determine if a value is an array.
  7. length – Determine the size of an array.

The concat() array method

The concat() method merges one or more arrays and returns a merged array it is an immutable method

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]
Enter fullscreen mode Exit fullscreen mode

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

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

The join() array method

The join() method joins all the elements of the array using a separator and returns a string.

const emotions = ['πŸ™‚', '😍', 'πŸ™„', '😟'];

const joined = emotions.join();
console.log(joined); // "πŸ™‚,😍,πŸ™„,😟"
Enter fullscreen mode Exit fullscreen mode

You can pass a separator of your choice to join the elements

const joined = emotions.join('<=>');
console.log(joined); // "πŸ™‚<=>😍<=>πŸ™„<=>😟"
Enter fullscreen mode Exit fullscreen mode

Invoking the join() method on an empty array returns an empty string:

[].join() // returns ""
Enter fullscreen mode Exit fullscreen mode

The fill() array method

The fill method fills an array with a static value. You can
change all the elements to a static value or change a few selected items.fill method changes the original array

const colors = ['red', 'blue', 'green'];

colors.fill('pink');
console.log(colors); // ["pink", "pink", "pink"]
Enter fullscreen mode Exit fullscreen mode

Here is an example where we are changing only the last two elements of the array using the fill() method:

const colors = ['red', 'blue', 'green'];

colors.fill('pink', 1,3); // ["red", "pink", "pink"]
Enter fullscreen mode Exit fullscreen mode

In this case the first argument of fill method is the value we change with. The second argument is the start index to change.
The last argument is to determine where to stop filling

The indexOf() array method

You may want to know the index position of an element in array. You can use 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 names = ['tom', 'alex', 'bob', 'john'];

names.indexOf('alex'); // returns 1
names.indexOf('rob'); // returns -1
Enter fullscreen mode Exit fullscreen mode

There is another method lastIndexOf() that helps you find the index of the last occurrence of an element in the array. Like indexOf(), lastIndexOf() also returns -1 if the element is not found.

const names = ['tom', 'alex', 'bob', 'tom'];

names.indexOf('tom'); // returns 0
names.lastIndexOf('tom'); // returns 3
Enter fullscreen mode Exit fullscreen mode

The reverse() array method

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 names = ['tom', 'alex', 'bob'];

names.reverse(); // returns ["bob", "alex", "tom"]
Enter fullscreen mode Exit fullscreen mode

The sort() array method

The sort method is probably one of the most often used array methods.The default sort() method converts the element types into strings and then sorts them. The default sorting order is ascending. The sort() method changes the original array.

const names = ['tom', 'alex', 'bob'];

names.sort(); // returns ["alex", "bob", "tom"]
Enter fullscreen mode Exit fullscreen mode

The sort() method accepts an optional comparator function as an argument. You can write a comparator function and pass to the sort() method to override the default sorting behavior.

Let's now take an array of numbers and sort them in ascending and descending order using a comparator function:

const numbers = [23, 5, 100, 56, 9, 13, 37, 10, 1]
numbers.sort();

Now the sorted array is, [1, 10, 100, 13, 23, 37, 5, 56, 9]. Well, that's not the output we expect. But it happens because the default sort() method converts the elements to a string and then compares them based on the UTF-16 code unit values.

To solve this, let's write a comparator function. Here is one for the ascending order:

function ascendingComp(a, b){
  return (a-b);
}
Enter fullscreen mode Exit fullscreen mode

Now pass this to the sort() method:

numbers.sort(ascendingComp); // retruns [1, 5, 9, 10, 13, 23, 37, 56, 100]

/* 

We could also code it like,

numbers.sort(function(a, b) {
  return (a-b);
});

Or, with the arrow function,

numbers.sort((a, b) => (a-b));

*/
Enter fullscreen mode Exit fullscreen mode

The splice() array method

The splice() method helps you add, update, and remove elements in an array

The splice() method is to delete elements from array. It returns an array of the elements deleted and modifies the original array. But you can add and replace elements using it as well.

To add an element using the splice() method, we need to pass the position where we want to add, how many elements to delete starting with the position, and the element to add.

In the example below, we are adding an element jack at the index 1 without deleting any elements.

const names = ['tom', 'alex', 'bob'];

names.splice(1, 0, 'jack');

console.log(names); // ["tom", "jack", "alex", "bob"]
Enter fullscreen mode Exit fullscreen mode

Have a look at the following example. Here we are removing one element from the index 2 (the 3rd element) and adding a new element, jack. The splice() method returns an array with the deleted element, bob.

const names = ['tom', 'alex', 'bob'];

const deleted = names.splice(2, 1, 'jack');

console.log(deleted); // ["bob"]
console.log(names); // ["tom", "alex", "jack"]
Enter fullscreen mode Exit fullscreen mode

Array Iterator Methods

These are very useful methods for iterating through array and performing computations, making decisions, filtering out stuff, and more.

let students = [
   {
      'id': 001,
      'f_name': 'Alex',
      'l_name': 'B',
      'gender': 'M',
      'married': false,
      'age': 22,
      'paid': 250,  
      'courses': ['JavaScript', 'React']
   },
   {
      'id': 002,
      'f_name': 'Ibrahim',
      'l_name': 'M',
      'gender': 'M',
      'married': true,
      'age': 32,
      'paid': 150,  
      'courses': ['JavaScript', 'PWA']
   },
   {
      'id': 003,
      'f_name': 'Rubi',
      'l_name': 'S',
      'gender': 'F',
      'married': false,
      'age': 27,
      'paid': 350,  
      'courses': ['Blogging', 'React', 'UX']
   },
   {
      'id': 004,
      'f_name': 'Zack',
      'l_name': 'F',
      'gender': 'M',
      'married': true,
      'age': 36,
      'paid': 250,  
      'courses': ['Git', 'React', 'Branding']
   } 
];
Enter fullscreen mode Exit fullscreen mode

The filter() array method

The filter() method creates a new array with all the elements that satisfies the condition mentioned in the function. Let's find the student who is female. So the filter condition should be that the gender is equal to 'F'.

const femaleStudents = students.filter((element, index) => {
  return element.gender === 'F';
})

console.log(femaleStudents);
Enter fullscreen mode Exit fullscreen mode

That's right. The student with name Rubi is the only female student we have got so far and it will return that

The map() array method

The map() method creates a new array by iterating through the elements and applying logic we provided in the function as an argument. We'll create a new array of full names of all the students in the students array.

const fullNames = students.map((element, index) => {
  return {'fullName': element['f_name'] + ' ' + element['l_name']}
});

console.log(fullNames);
Enter fullscreen mode Exit fullscreen mode

Image description

Here we see a new array with the fullName properties that is computed using the f_name and l_name properties of each student object.

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
Enter fullscreen mode Exit fullscreen mode

The find() array method

To do that, we will use the find() method. It returns the first matched element from the array that satisfies the condition in the function.

Arrays have another related method, findIndex(), that returns the index of the element we find using the find() method. If no elements match the condition, the findIndex() method returns -1.

In the example below, we pass a function to the find() method that checks for the age of each of the student. It returns the matched student when the condition satisfies.

const student = students.find((element, index) => {
  return element.age < 30;
});

console.log(student);
Enter fullscreen mode Exit fullscreen mode

Image description

The every() array method

The every() method detects if every element of the array satisfies the condition passed in the function. Let's find if all the students have subscribed to at least two courses.

const atLeastTwoCourses = students.every((elements, index) => {
  return elements.courses.length >= 2;
});

console.log(atLeastTwoCourses); // true
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
sangeethpsk
sangeethpsk

Posted on May 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related