Comments

Most Common Array Operations That You Should Learn In JavaScript

Array Operations

In this post, we are going to take a detailed look at the most common Array operations that you should learn in JavaScript. These operations are very important in JavaScript programming, especially if you are just starting to learn JavaScript.

Adding Elements

We have 3 methods to add elements to an array, depending on where we want these elements to be inserted.

Array.prototype.push

We can use the push method to add one or more elements to the end of an array.

const numbers = [3, 4];
numbers.push(5, 6); 
// numbers: [3, 4, 5, 6]

Array.prototype.unshift

We can use the unshift method to add one or more elements to the beginning of an array.

const numbers = [3, 4];
numbers.unshift(1, 2);   
// numbers: [1, 2, 3, 4]

Array.prototype.splice

We can use the splice method to add one or more elements somewhere in the middle of an array.

const numbers = [1, 2, 3, 4, 5, 6];
numbers.splice(2, 0, 'a', 'b');  
// numbers: [1, 2, "a", "b", 3, 4, 5, 6]

The splice method accepts three parameters as shown below.

  • The index where you want to start inserting one or more new elements.
  • The number of elements to remove from the array starting at the index specified in the first parameter.
  • One or more elements to insert into the array at the index specified in the first parameter.

Removing Elements

We have 3 methods to remove elements from an array, depending on where we want these elements to be removed from.

Array.prototype.pop

We can use the pop method to remove the last element of the array and return the value of this element.

const numbers = [1, 2, 3, 4];
var last = numbers.pop();
// last: 4
// numbers: [1, 2, 3]

Array.prototype.shift

We can use the shift method to remove the first element of the array and return the value of this element.

const numbers = [1, 2, 3, 4];
var first = numbers.shift();
// first: 1
// numbers: [2, 3, 4]

Array.prototype.splice

We can use the splice method to remove one or more elements from somewhere in the middle of an array.

const numbers = [1, 2, 3, 4];
var splice = numbers.splice(1, 2);
// splice: [1, 4]

Below are the parameters related to this method for removing one or more elements.

  • The index where you want to start removing one or more elements from the array.
  • The number of elements to remove from the array starting at the index specified in the first parameter.

Complex Array Operations (Higher Order Functions)

We saw the basic adding, and removing items from an array. Now let’s dive into some complex Array operations that come handy when you are coding.

JavaScript comes with some built-in higher-order functions that operate on arrays. You may already be using them, without realising that they are higher-order functions. Let’s take a look at some of them, to understand how they work.

A function that accepts and/or returns another function is called a higher-order function.

Array.prototype.sort

Sorting an array is one of the most common tasks that you will perform during your programming career. The sort() method sorts the elements of an array in place and returns the sorted array. The syntax of the sort() method is below.

arr.sort([compareFunction])

Here the compareFunction refers to the sorting order. This is an optional parameter. If the sort order is not provided, the array elements are converted to strings, then sorted according to each character’s Unicode code point value.

A compare function can take the following form.

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

In case you are sorting an array of numbers, then the compare() function is even simpler.

function compareNumbers(a, b) {
  return a - b;
}

The example will sort the array of numbers in ascending order. With the use of the arrow function, the code is simplified further.

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]

Array.prototype.map

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map() calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

The callback accepts three arguments:

  • value of the element
  • index of the element
  • array object

You may have used the map() function before. It qualifies as a higher-order function, because it takes in a callback function as an input argument.

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
  return num * 2;
});

// doubles is now [2, 8, 18]
// numbers is still [1, 4, 9]

In the example above, we have an array of numbers and creating a new array using the map(). The map() takes a function as an argument. The argument num within the function will automatically be assigned from each element of the array as map() loops through the original array.

Array.prototype.filter

The filter() method is another example of an in-built higher-order function. It creates a new array with all the elements that pass the test provided by a callback function. The callback function passed to the filter() method accepts three arguments:

  • value of the element
  • index of the element
  • array object

Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

Let’s take a look at an example that shows filter() in action.

function isAboveMyRange(value) {
  return value >= 25;
}
var filtered = [12, 5, 8, 130, 44].filter(isAboveMyRange);
// filtered is [130, 44]

The values that don’t pass this test, will not be a part of the filtered array. The filter() function takes the isAboveMyRange function as an input parameter.

Array.prototype.reduce

Another built-in higher-order function in JavaScript is the reduce() method. It executes the callback function on each member of the calling array, and results in a single output value. The reduce() method takes in two input parameters:

  • The reducer callback function (making this method a higher-order function)
  • Optional initial value
arr.reduce(callback[, initialValue])

The reducer function (callback) accepts four parameters:

  • accumulator
  • currentValue
  • currentIndex
  • sourceArray

If an initialValue is provided, then the accumulator will be equal to the initialValue, and the currentValue will be equal to the first element in the array. Suppose no initialValue is provided, then the accumulator will be equal to the first element in the array and the currentValue will be equal to the second element in the array. Let’s try to understand this better with a simple example.

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// sum is 6

In this example, we have passed an initialValue of zero, this is assigned to the accumulator in the beginning. Every time the reduce() function is called on each value in the array, the accumulator keeps the result of previous operation returned from the function, and the currentValue is set to the current value of the array. In the end the result is stored in the sum variable.

Conclusion

In this article, we learned some common Array Operations in JavaScript.

Mosh has a bundle of amazing courses out there that will enable you to become proficient in JavaScript. Checkout the course below to become a JavaScript master.

Mosh’s JavaScript Course Bundle

If you enjoyed this post, share and spread the word. You can follow me on twitter at @AdhithiRavi

Adhithi Ravichandran is a Software Consultant based in Kansas City. She is currently working on building apps with React, React Native and GraphQL. She is a Conference Speaker, Pluralsight Author, Blogger and Software Consultant. She is passionate about teaching and thrives to contribute to the tech community with her courses, blog posts and speaking engagements.
Tags: ,

2 responses to “Most Common Array Operations That You Should Learn In JavaScript”

  1. Alejandro Montes says:

    Very useful!!! thank you 🙂

Leave a Reply

Connect with Me
  • Categories
  • Popular Posts