Introduction

A method is a function which is a property of an object. There are two kind of methods: Instance Methods which are built-in tasks performed by an object instance, or Static Methods which are tasks that are called directly on an object constructor.

Add Items to an Array

Array.push()

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

Mutates the original array!

Functional programming alternative: Array.concat().


let twentyThree = 'XXIII';
      
let romanNumerals = ['XXI', 'XXII'];

romanNumerals.push(twentyThree);
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.

Array.unshift()

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

Mutates the original array!


let twentyThree = 'XXIII';
      
let romanNumerals = ['XXI', 'XXII'];

romanNumerals.unshift('XIX', 'XX');
// now equals ['XIX', 'XX', 'XXI', 'XXII']

Array.concat()

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.


[1, 2, 3].concat([4, 5, 6]);
// Returns a new array [1, 2, 3, 4, 5, 6]

Remove Items from an Array

Array.pop()

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

Mutates the original array!


let greetings = ['whats up?', 'hello', 'see ya!'];

greetings.pop();
// now equals ['whats up?', 'hello']

// We can also return the value of the removed element like this:
let popped = greetings.pop();
// returns 'hello'
// greetings now equals []

Array.shift()

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

Mutates the original array!


let greetings = ['whats up?', 'hello', 'see ya!'];

greetings.shift();
// now equals ['hello']

// We can also return the value of the removed element like this:
let shifted = greetings.shift();
// returns 'hello'
// greetings now equals []

Add, Remove, and Copy Items from an Array

Array.splice()

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

Parameters:

  1. Represents the index on the array from which to begin removing elements.
  2. Indicates the number of elements to delete.
  3. Comprised of one or more element(s), to add to the array.

If the second argument is not provided, the default is to remove items through the end.

Mutates the original array!

Functional programming alternative: Array.slice().

Demonstrates parameters 1 and 2:


let array = ['today', 'was', 'not', 'so', 'great'];

array.splice(2, 2);
// remove 2 elements beginning with the 3rd element
// array now equals ['today', 'was', 'great']

// It modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
let array = ['I', 'am', 'feeling', 'really', 'happy'];

let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']

Demonstrates parameter 3:


const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;

numbers.splice(startIndex, amountToDelete, 13, 14);
// the second entry of 12 is removed, and we add 13 and 14 at the same index
console.log(numbers);
// returns [ 10, 11, 12, 13, 14, 15 ]

Array.slice()

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) where begin and end represent the index of items in that array. The original array will not be modified.

Parameters:

  1. The index at which to begin extraction.
  2. The index at which to stop extraction (extraction will occur up to, but not including the element at this index).

If the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array.


let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];

let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']

Check for the Presence of an Element in an Array

Array.indexOf()

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.

Parameters:

  1. Takes an element as a parameter, and when called, it returns the position, or index, of that element, or -1 if the element does not exist on the array.

let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];

fruits.indexOf('dates'); // returns -1
fruits.indexOf('oranges'); // returns 2
fruits.indexOf('pears'); // returns 1, the first index at which the element exists

Extract Data from an Array

Array.map()

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

Parameters:

  1. The current element being processed.
  2. The index of that element.
  3. The array upon which the map method was called.

This example utilizes only the first parameter:


const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }
];

const names = users.map(user => user.name);
console.log(names); // [ 'John', 'Amy', 'camperCat' ]

Array.filter()

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

Parameters:

  1. The current element being processed.
  2. The index of that element.
  3. The array upon which the filter method was called.

This example utilizes only the first parameter:


const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }
];

const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]

Analyze Data in an Array

Array.reduce()

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Parameters:

  1. Callback Function Arguments:
    1. Known as the accumulator, it gets assigned the return value of the callback function from the previous iteration.
    2. The current element being processed.
    3. The index of that element.
    4. The array upon which reduce is called.
  2. Takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator.

These examples utilize both parameters and only the first and second arguments of the first parameter.

Example 1: Sum of all ages


const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }
];

const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64

Example 2: Property and value pairs


const users = [
  { name: 'John', age: 34 },
  { name: 'Amy', age: 20 },
  { name: 'camperCat', age: 10 }
];

const usersObj = users.reduce((obj, user) => {
  obj[user.name] = user.age;
  return obj;
}, {});
console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 }

Sort an Array

Array.sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called compareFunction, is supplied, the array elements are sorted according to the return value of the compareFunction: If compareFunction(a,b) returns a value less than 0 for two elements a and b, then a will come before b. If compareFunction(a,b) returns a value greater than 0 for two elements a and b, then b will come before a. If compareFunction(a,b) returns a value equal to 0 for two elements a and b, then a and b will remain unchanged.

Mutates the original array!


function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]);
// Returns [1, 2, 3, 4, 5]

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? 1 : -1;
  });
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']

Functional programming alternative: first concatenate an empty array to the one being sorted (remember that slice and concat return a new array), then run the sort method, like below:


var globalArray = [5, 6, 3, 2, 9];

function nonMutatingSort(arr) {
  return [].concat(arr).sort(function(a, b) {
    return a - b;
  });
}
nonMutatingSort(globalArray);

Array.reverse()

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

Mutates the original array!


const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

String-to-Array & Array-to-String

Str.split()

The split() method turns a String into an array of strings, by separating the string at each instance of a specified separator string.

Parameters:

  1. Can be a character to use to break up the string or a regular expression (For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string).

var str = "Hello World";
var bySpace = str.split(" ");
// Sets bySpace to ["Hello", "World"]

var otherString = "How9are7you2today";
var byDigits = otherString.split(/\d/);
// Sets byDigits to ["How", "are", "you", "today"]

Array.join()

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Parameters:

  1. Used to separate the array elements in the string.

var arr = ["Hello", "World"];
var str = arr.join(" ");
// Sets str to "Hello World"

Check Criteria of the Elements in an Array

Array.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Caution: Calling this method on an empty array will return true for any condition!

The following code would check if every element in the numbers array is less than 10:


var numbers = [1, 5, 8, 0, 10, 11];
numbers.every(function(currentValue) {
  return currentValue < 10;
});
// Returns false

Array.some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

Caution: Calling this method on an empty array returns false for any condition!

The following code would check if any element in the numbers array is less than 10:


var numbers = [10, 50, 8, 220, 110, 11];
numbers.some(function(currentValue) {
  return currentValue < 10;
});
// Returns true

References

All of the definitions on this page are from MDN. Most of the code snippets and notes are from freeCodeCamp.