Does it mutate?

No mutation

.concat

No mutation


Description

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Array.prototype.concat ( [ item1 [ , item2 [ , … ] ] ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat


Example

var array1 = ['a', 'b', 'c']; var array2 = ['d', 'e', 'f']; console.log(array1.concat(array2)); // expected output: Array ["a", "b", "c", "d", "e", "f"] 


.copyWithin()



Description

The copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.

arr.copyWithin(target) arr.copyWithin(target, start) arr.copyWithin(target, start, end) 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin


Example

var array1 = ['a', 'b', 'c', 'd', 'e']; // copy to index 0 the element at index 3 console.log(array1.copyWithin(0, 3, 4)); // expected output: Array ["d", "b", "c", "d", "e"] // copy to index 1 all elements from index 3 to the end console.log(array1.copyWithin(1, 3)); // expected output: Array ["d", "d", "e", "d", "e"] 
.entries()



Description

The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.

a.entries()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries


Example

var array1 = ['a', 'b', 'c']; var iterator1 = array1.entries(); console.log(iterator1.next().value); // expected output: Array [0, "a"] console.log(iterator1.next().value); // expected output: Array [1, "b"] 
.every



Description

The every() method tests whether all elements in the array pass the test implemented by the provided function.

Array.prototype.every ( callbackfn [ , thisArg ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every


Example

function isBelowThreshold(currentValue) { return currentValue < 40; } var array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold)); // expected output: true 
.fill()



Description

The fill() method fills all the elements of an array from a start index to an end index with a static value.

arr.fill(value) arr.fill(value, start) arr.fill(value, start, end) 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill


Example

var array1 = [1, 2, 3, 4]; // fill with 0 from position 2 until position 4 console.log(array1.fill(0, 2, 4)); // expected output: [1, 2, 0, 0] // fill with 5 from position 1 console.log(array1.fill(5, 1)); // expected output: [1, 5, 5, 5] console.log(array1.fill(6)); // expected output: [6, 6, 6, 6] 
.filter



Description

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.filter ( callbackfn [ , thisArg ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


Example

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"] 
.find()



Description

The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

arr.find(callback[, thisArg])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find


Example

var array1 = [5, 12, 8, 130, 44]; var found = array1.find(function(element) { return element > 10; }); console.log(found); // expected output: 12 
.findIndex()



Description

The findIndex() method returns an index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

arr.findIndex(callback[, thisArg])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex


Example

var array1 = [5, 12, 8, 130, 44]; function isLargeNumber(element) { return element > 13; } console.log(array1.findIndex(isLargeNumber)); // expected output: 3 
.forEach



Description

The forEach() method executes a provided function once per array element.

Array.prototype.forEach ( callbackfn [ , thisArg ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach


Example

var array1 = ['a', 'b', 'c']; array1.forEach(function(element) { console.log(element); }); // expected output: "a" // expected output: "b" // expected output: "c" 
.includes()



Description

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

arr.includes(searchElement) arr.includes(searchElement, fromIndex) 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes


Example

var array1 = [1, 2, 3]; console.log(array1.includes(2)); // expected output: true var pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // expected output: true console.log(pets.includes('at')); // expected output: false 
.indexOf



Description

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Array.prototype.indexOf ( searchElement [ , fromIndex ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf


Example

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4 console.log(beasts.indexOf('giraffe')); // expected output: -1 
.join



Description

The join() method joins all elements of an array into a string.

Array.prototype.join (separator)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join


Example

var elements = ['Fire', 'Wind', 'Rain']; console.log(elements.join()); // expected output: Fire,Wind,Rain console.log(elements.join('')); // expected output: FireWindRain console.log(elements.join('-')); // expected output: Fire-Wind-Rain 
.keys()



Description

The keys() method returns a new Array Iterator that contains the keys for each index in the array.

arr.keys()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys


Example

var array1 = ['a', 'b', 'c']; var iterator = array1.keys(); for (let key of iterator) { console.log(key); // expected output: 0 1 2 } 
.lastIndexOf



Description

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf


Example

var animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; console.log(animals.lastIndexOf('Dodo')); // expected output: 3 console.log(animals.lastIndexOf('Tiger')); // expected output: 1 
.map



Description

The map() method creates a new array with the results of calling a provided function on every element in this array.

Array.prototype.map ( callbackfn [ , thisArg ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


Example

var array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32] 
.pop



Description

The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

Array.prototype.pop ( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop


Example

var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // expected output: "tomato" console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage"] 
.push



Description

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Array.prototype.push ( [ item1 [ , item2 [ , … ] ] ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push


Example

var animals = ['pigs', 'goats', 'sheep']; console.log(animals.push('cows')); // expected output: 4 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"] animals.push('chickens'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens"] 
.reduce



Description

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Array.prototype.reduce ( callbackfn [ , initialValue ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce


Example

const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log(array1.reduce(reducer)); // expected output: 10 // 5 + 1 + 2 + 3 + 4 console.log(array1.reduce(reducer, 5)); // expected output: 15 
.reduceRight



Description

The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) has to reduce it to a single value.

Array.prototype.reduceRight ( callbackfn [ , initialValue ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight


Example

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue) ); console.log(array1); // expected output: Array [4, 5, 2, 3, 0, 1] 
.reverse



Description

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

Array.prototype.reverse ( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse


Example

var array1 = ['one', 'two', 'three']; console.log('array1: ', array1); // expected output: Array ['one', 'two', 'three'] var reversed = array1.reverse(); console.log('reversed: ', reversed); // expected output: Array ['three', 'two', 'one'] /* Careful: reverse is destructive. It also changes the original array */ console.log('array1: ', array1); // expected output: Array ['three', 'two', 'one'] 
.shift



Description

The shift() method removes the first element from an array and returns that element. This method changes the length of the array.

Array.prototype.shift ( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift


Example

var array1 = [1, 2, 3]; var firstElement = array1.shift(); console.log(array1); // expected output: Array [2, 3] console.log(firstElement); // expected output: 1 
.slice



Description

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Array.prototype.slice (start, end)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


Example

var animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"] 
.some



Description

The some() method tests whether some element in the array passes the test implemented by the provided function.

Array.prototype.some ( callbackfn [ , thisArg ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some


Example

var array = [1, 2, 3, 4, 5]; var even = function(element) { // checks whether an element is even return element % 2 === 0; }; console.log(array.some(even)); // expected output: true 
.sort



Description

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

Array.prototype.sort (comparefn)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


Example

var months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"] var array1 = [1, 30, 4, 21]; array1.sort(); console.log(array1); // expected output: Array [1, 21, 30, 4] 
.splice



Description

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

Array.prototype.splice (start, deleteCount [ , item1 [ , item2 [ , … ] ] ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice


Example

var months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // inserts at 1st index position console.log(months); // expected output: Array ['Jan', 'Feb', 'March', 'April', 'June'] months.splice(4, 1, 'May'); // replaces 1 element at 4th index console.log(months); // expected output: Array ['Jan', 'Feb', 'March', 'April', 'May'] 
.toLocaleString



Description

The toLocaleString() method returns a string representing the elements of the array. The elements are converted to Strings using their toLocaleString methods and these Strings are separated by a locale-specific String (such as a comma “,”).

Array.prototype.toLocaleString ( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString


Example

var array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')]; var localeString = array1.toLocaleString('en', {timeZone: "UTC"}); console.log(localeString); // expected output: "1,a,12/21/1997, 2:12:00 PM", // This assumes "en" locale and UTC timezone - your results may vary 
.toSource()



Description

The toSource() method returns a string representing the source code of the array.

arr.toSource()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSource


Example


.toString



Description

The toString() method returns a string representing the specified array and its elements.

Array.prototype.toString ( )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString


Example

var array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // expected output: "1,2,a,1a" 
.unshift



Description

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Array.prototype.unshift ( [ item1 [ , item2 [ , … ] ] ] )

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift


Example

var array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // expected output: 5 console.log(array1); // expected output: Array [4, 5, 1, 2, 3] 
.values()



Description

The values() method returns a new Array Iterator object that contains the values for each index in the array.

arr.values()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values


Example

const array1 = ['a', 'b', 'c']; const iterator = array1.values(); for (const value of iterator) { console.log(value); // expected output: "a" "b" "c" } 


All about JavaScript Arrays Methods

All about JavaScript Arrays Methods

Everything You Need to Know About JavaScript Array Methods

Web development or web programming gave birth to dynamic web applications. With the rise of the web, JavaScript has become one of the most important languages in today’s world. This **JavaScript Array **article will take you to the depths of array methods in JavaScript in the following sequence:

  • Introduction to JavaScript
  • Fundamentals of JavaScript
  • JavaScript Array
  • Difference between Array and Objects
  • JavaScript Array Methods
Introduction to JavaScript

JavaScript is a high level, interpreted, programming language used to make web pages more interactive. It is a very powerful client-side scripting language which makes your webpage more lively and interactive.

It is a programming language that helps you to implement a complex and beautiful design on web pages. If you want your web page to look alive and do a lot more than just gawk at you, JavaScript is a must.

Fundamentals of JavaScript

If you are new to the language, you need to know some of the fundamentals of JavaScript that will help you start writing your code. The basics include:

JavaScript Array

An array is a data structure that contains a list of elements which store multiple values under a single variable.

To declare an array in JavaScript use the ‘let’ keyword with square brackets and enclose all the elements within them. The syntax is as follows:

let ListItems=[];
ListItems=['shoes','watch','bag'];

You can also declare it as:

let ListItems=['shoes','watch','bag'];

Difference between Array and Objects

JavaScript variables can be objects. Arrays are considered to be special kinds of objects. Because of this, you can have variables of different types in the same Array.

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myItems;

In JavaScript, arrays use numbered indexes. Whereas, objects are used as named indexes.

JavaScript Array Methods

The purpose of using an array is to store** multiple values** in a single entity of a declared variable. Arrays are used when we want to access elements in an orderly fashion using a single variable. One can store strings, boolean and numbers in a single array.

There are different JavaScript array methods in order to perform various tasks such as:
push() – It is easy to remove elements and add new elements while working with arrays. The push() method adds a new element to the end of an array. The return value is the new array length.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.push('watch'));

Output:

4

Push() doest not return the value that has been added to the array. It only returns the new length of the array.
**pop() – **The pop() method is used to remove the last element from an array. It returns the value that has been popped out.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.pop());

Output:

dress

Pop() returns the value that has been removed and not the array length like Push().
shift() – Shifting is similar to popping, working on the first element instead of the last. The shift() method is used to remove the first array element and shifts all other elements to a lower index. It will return you the string that has been shifted out.
Example:

let listItems = ['bag','shoes','dress'];
console.log(listItems.shift());

Output:

bag

Shift() works same as pop() but it returns the first element of the array instead of the last one.
unshift() – The unshift() method adds a new element at the beginning of an array and unshifts older elements. It is similar to Push() and returns the new array length.
**Example: **

let listItems = ['bag','shoes','dress','watch'];
console.log(listItems.unshift('phone'));

Output:

5

Unshift() will add the new element into the array and return the length of the new array.
concat() – The concat() method creates a new array by concatenating or merging existing arrays. It does not modify the existing array and always returns a new array.
Example:

let arr1 = ['red','blue','green'];
let arr2 = ['colors','spraypaint', 'brush'];
let newArr = arr1.concat(arr2);
console.log(newArr);

Output:


toString() – The toString() method is used to convert an array to a string of array values, separated by commas.
Example:

let colors = ['red','blue','green'];
console.log(colors.toString());

Output:

red,blue,green

join() – The join() method works same as toString(). It is used to join all array elements into a string, but in addition, you can specify the separator.
Example:

let colors = ['red','blue','green'];
console.log(colors.join("+"));

Output:

red+blue+green

reverse() – The reverse() method is used to reverse the order of the elements in an array. It will change the original array and swap the order of the elements.
Example:

let fruits = ['mango','apple','grapes'];
console.log(fruits.reverse());

Output:


sort() – The sort() method is used to sort an array alphabetically. This function sorts the values as string by default.
Example:

let fruits = ['mango','apple','grapes'];
console.log(fruits.sort());

Output:


slice() – The slice() method is used to slice out a piece of an array into a new array. It creates a new array without removing any elements from the source array. It will return the value that has been sliced out from the array.
Example:

let colors = ['red','blue','green','yellow','orange'];
console.log(colors.slice(1,3));

Output:

These were some of the most commonly used JavaScript array methods. With this, we have come to the end of our article. I hope you understood how array methods are used in JavaScript.

How to reverse an array in JavaScript?

How to reverse an array in JavaScript?

Here's a Code Recipe to keep around if you need to reverse the order of the elements of an array. You can use the array method, "reverse()" ⏪

Trying a new segment called #CodeRecipes. I want to cover questions that I often google. These are recipes that you should definitely keep handy because it's not a matter "if" you use it, but "when" 😉

const benjamin = ['👶','👦', '👨', '👴'];

const benjaminButton = benjamin.reverse();

console.log(benjaminButton);
// ['👴', '👨', '👦', '👶']

Modifies Original Array

One thing to note is that it mutates the original array.

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reverse();

console.log(originalArray); // [ 'c', 'b', 'a' ]
console.log(newArray); // [ 'c', 'b', 'a' ]

How to Reverse Array Without Mutating Original Array

Here are some recipes that won't mutate the original array. Let's take a look 👀

Using slice and reverse

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.slice().reverse();

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using spread and reverse

const originalArray = ['a', 'b', 'c'];
const newArray = [...originalArray].reverse();

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using reduce and spread

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduce((accumulator, value) => {
  return [value, ...accumulator]
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Using reduceRight and spread

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
  console.log(value);
  return [...accumulator, value]
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Or using push

const originalArray = ['a', 'b', 'c'];
const newArray = originalArray.reduceRight((accumulator, value) => {
  accumulator.push(value);
  return accumulator;
}, []);

console.log(originalArray); // ['a', 'b', 'c']
console.log(newArray); // [ 'c', 'b', 'a' ]

Source code and tests are available here

Resources

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?