Array methods in JavaScript (2018 Update)

javascript array methods

The array is one of the most important components of JavaScript, and any programming language in general. Often misconceived as its own data type, it is actually a subset of the Object, along with functions. In simple terms, an array is a compound data structure that can hold a limitless amount of values of any type. Each of the values is numerically indexed (i.e. each value has a number, designating its position in the array). This makes the array extremely flexible for storing and organizing data. Arrays can store strings, numbers, objects, or even other arrays. This post will give an overview of some of the most commonly used built-in JavaScript array methods. You can use these methods or functions to manipulate and deal with the data inside an array.

concat()

The concat() method, short for “concatenate”, allows us to join two arrays together:

var colors = ["black", "white", "blue"];
var colors2 = ["green", "yellow", "purple"];

document.write(colors.concat(colors2));
// output: "black, white, blue, green, yellow, purple"

 

On its own, concat() will not alter the original array the method was called on. Calling colors will still output the original array with only 3 values. In order to update the original array, you’d need to call the method on the colors array, re-assigning the variable:

On its own, concat() will not alter the original array you call the method on. Calling colors will still output the original array with only 3 values. To update the original array, you’d need to call the method on the colors array, re-assigning the variable:

colors = colors.concat(colors1); 

 

push()

Often you will just want to add new items to the end of an array, which you can use the push() method for. You can push either a single or multiple values to an array in the same call:

var colors = ["black", "white", "blue"];
colors.push("green", "yellow");

document.write(colors);
// output: "black, white, blue, green, yellow"

 

Unlike concat(), push() does update the original array with the values that you’ve pushed to it.

unshift()

Similar to push(), unshift() will add one or more new values to the beginning of the array:

var colors = ["black", "white", "blue"];
colors.unshift("green");

document.write(colors);
// output: "green, black, white, blue"

 

pop()

pop() is the inverse of the push() method, in that it will “pop” off or remove the last element of an array:

var colors = ["black", "white", "blue"];
colors.pop();

document.write(colors);
// output: "black, white" 

 

Since pop() removes an item from an array, it is common to store the removed item into another variable for other uses:

var lastItem = colors.pop();

document.write(lastItem);
// output: "blue"

 

shift()

Similarly, shift() will remove the first item in an array:

var colors = ["black", "white", "blue"];
colors.shift();

document.write(colors);
// output: "white, blue"; 

 

You can also use shift() in tandem with storing the removed item in a new variable:

var firstItem = colors.shift();

document.write(firstItem);
// output: "black" 

 

reverse()

As the name implies, the reverse() method will reverse the ordering of the values in the array:

var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var reversedArray = myArray.reverse();

document.write(reversedArray);
// output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

 

reverse() will not alter the original array. You’ll need to store the reversed array in a new variable. Alternatively you can re-assign it to the original variable in order to keep the reversed changes.

join()

The join() array method will join all values in the array into a string, then returning the string:

var colors = ["black", "white", "blue", "green"];
console.log(colors.join());
// output: black,white,blue,green 

 

There is an optional “separator” parameter that can be included with join(). This parameter indicates a character (or set of characters) to separate each value in the string. The example below will separate each value with a comma followed by a whitespace character:

var colors = ["black", "white", "blue", "green"];
console.log(colors.join(', ');
// output: black, white, blue, green 

 

join() will not modify the original array. You’ll need to assign the modification to a variable in order to save it.

var colorList = colors.join(', ');
console.log(colorList);
// output: black, white, blue, green

console.log(colors);
// output: ["black", "white", "blue", "green"]
// i.e. still the original array

 

sort()

sort() will sort the values of an array in alphanumeric order. sort() does update the original array:

var arr1 = [4, 9, 3, 2, 1];
arr1.sort();
console.log(arr1);
// ouput: [1, 2, 3, 4, 9]

 

sort() only orders values at the time you call the method. You’ll need to call it again to re-sort if you add or modify values in the array.

indexOf()

indexOf() will return the index value of a search term provided as a string parameter to the method:

var colors = ["black", "white", "blue", "green"];
colors.indexOf('white');
// returns 1

 

If there is no index match for the searchValue parameter, indexOf() will return -1:

var colors = ["black", "white", "blue", "green"];
colors.indexOf('orange');
// returns -1

 

indexOf() is case sensitive:

colors.indexOf('Blue');
// returns -1

 

There is also an optional fromIndex parameter. This indicates from which index value the search should begin. If not supplied, search begins at index 0 by default:

var names = ["Michael", "John", "Sarah", "Michael", "Matthew"];
names.indexOf('Michael', 2);
// returns 3 

 

slice()

The slice() method will return a “slice” of the array, indicated by optional parameters for beginning and ending points. slice() leaves the original array unmodified:

The slice() method will return a “slice” of the array. You can indicate beginning and ending points via its optional parameters. slice() leaves the original array unmodified:

var colors = ["black", "white", "blue", "green", "purple", "orange"];
var colors2 = colors.slice(2, 5);
console.log(colors2);
// output: ["blue", "green", "purple"]

var colors3 = colors.slice(1);
console.log(colors3);
// output: ["white", "blue", "green", "purple", "orange"];

console.log(colors);
// output: ["black", "white", "blue", "green", "purple", "orange"]; 

 

filter()

filter() is somewhat similar to the slice() method. The main difference is that it creates a new array based upon certain conditions. Each value in the array that passes a condition is “filtered” into the new array. The condition for filtering is set via the callback function:

var someWords = ["easy", "hard", "encryption", "society", "total", "fastidious", "complexity"];

function checkSize(w) {
    return w.length > 5;
}

var bigWords = someWords.filter(checkSize);
console.log(bigWords);
// output: ["encryption", "society", "fastidious", "complexity"] 

 

The example above uses the checkSize() callback function to filter out any words less than 6 characters long. It also puts all the remaining values in a new array called bigWords.

every()

The every() array method will check to see if every value in the array passes a condition or not. The condition here is also provided via a callback function. If it passed, the method will return true, if it does not, it will return false:

var nums = [20, 31, 18, 500];

function greaterThan10 (value) {
    return value > 10;
}

console.log(nums.every(greaterThan10));
// output: true

 

The example above tests to see if every value in the nums array is greater than 10, returning true.

isArray()

As the name implies, .isArray() will check to see whether a value passed to it is an array or not:

Array.isArray(['blue', 'yellow' 'green']);  // returns true
Array.isArray(3);                           // returns false
Array.isArray('hello');                     // returns false

 

findIndex()

findIndex() is almost the opposite of the indexOf() method. It will return the index of the first value in an array that satisfies a condition. The condition is set via a callback function. If no value is found that satisfies the condition then the function returns -1.

var colors = ['black', 'blue', 'yellow', 'green', 'purple'];

function greaterThanFive(e) {
    return e.length > 5;
}

var indexOfLargeValue = colors.findIndex(greaterThanFive);
console.log(indexOfLargeValue);
// output: 2

 

forEach()

The forEach() method will execute a callback function on every value in the array the method is called on. This is useful for adding values equally to each index in an array, as well as many other applications. This will not modify the original array, however, so the new values will need to be saved to another variable:

var nums = [1, 2, 3, 5, 8, 13];
var numsUpdated = [];

function addTwo(e) {
    e += 2;
    numsUpdated.push(e);
}

nums.forEach(addTwo);
console.log(numsUpdated);
// output: [3, 4, 5, 7, 10, 15]

 

This is similar to using a for loop to iterate over an array, with slightly more simple syntax.

includes()

You can use includes() to check whether a certain array contains a given a value or not. If the array does, it will return true, if it does not it will return false.

var colors = ['black', 'blue', 'yellow', 'green', 'purple'];

console.log(colors.includes('blue'));
// output: true

console.log(colors.includes('red'));
// output: false

 

There is an optional second parameter, fromIndex. This will indicate where to start the search from:

var colors = ['black', 'blue', 'yellow', 'green', 'purple'];

console.log(colors.includes('blue', 2));
// output: false

console.log(colors.includes('blue', 1));
// output: true

 

lastIndexOf()

Similar to indexOf(), lastIndexOf() will find the last instance of a given value in an array, as opposed to the first. The method will start its search from the end of the array and work its way to the beginning until a suitable match is found. If no match is found, the method will return -1:

var food = ['sushi', 'pizza', 'cheeseburger', 'sushi', 'pasta'];

console.log(food.lastIndexOf('sushi'));
// output: 3

console.log(food.lastIndexOf('burrito'));
// output: -1

 

.toString()

.toString() is somewhat similar to the .join() method, in that both can return the full index of values as a string. toString() is a far simpler method. It has no optional parameters for specifying “separator” characters to place between each value. All values in an array will simply be separated with a comma (with no spaces). This can be good or bad, depending on the application.

Resources

Post a Comment

Comments are moderated. Your email is kept private. Required fields are marked *

© 2018 Sunlight Media LLC - Web Design Company