Most Common Array Operations That You Should Learn In JavaScript

Most Common Array Operations That You Should Learn In JavaScript

In this article, 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.

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

New ES2019 Features Every JavaScript Developer Should Know

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

What JavaScript Framework You Should Learn to Get a Job in 2019?

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

Do we still need JavaScript frameworks?


javascript arrays web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

A quick guide to JavaScript Arrays

6 most commonly used methods and how they’re implemented. Arrays are a structure common to all programming languages so knowing what they are and having a firm grasp on what you’re able to accomplish with Arrays will take you a long way in your journey as a software developer.

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

6 Ways to Add Items to an Array in JavaScript

There are various ways to add or append an item to an array. We will make use of push, unshift, splice, concat, spread and index to add items to array. Let's discuss all the 6 different methods one by one in brief.

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.