JavaScript Array Methods Cheat-Sheet

by|inArticles||1 min read

This article contains a useful collection of common JavaScript Array methods with helpful example code snippets. It is very useful during software development in JavaScript projects.

pop() method

This method removes the last element from an array and returns that element.

let languages = ['PHP', 'JavaScript', 'Haskell'];

const lastLanguage = languages.pop();

console.log(laguages); // ["PHP", "JavaScript"]
console.log(lastLanguage); // "Haskell"

reduce() method

This method executes a reducer function on each element of the array and returns a single output value.

const wordCounts = [30,10,25];

const startValue = 0;
const reduceFunction = (value, accumulator) => value + accumulator;
const totalWordCount = wordCounts.reduce(reduceFunction, startValue);

console.log(totalWordCount); // 65

push() method

This method adds zero or more elements to the end of an array.

let languages = ['PHP', 'JavaScript', 'Haskell'];


console.log(languages); // ["PHP", "JavaScript", "Haskell", "PureScript"];

forEach() method

This method executes a provided function for each array element.

const languages = ['PHP', 'JavaScript', 'Haskell'];

languages.forEach(language => console.log(language));

// PHP
// JavaScript
// Haskell

find() method

This method returns the value of the first array element that satisfies the provided test function.

const numbers = [80, 96, 52, 14];

const result = numbers.find(item => item > 50);

console.log(result); // 80

sort() method

This method sorts the items of an array in a specific order (ascending or descending)

let languages = ['PHP', 'JavaScript', 'Haskell'];

let languagesSorted = languages.sort();

console.log(languagesSorted); // ['Haskell', 'JavaScript', 'PHP']

map() method

This method creates a new array with the result of calling a function for every array element.

let languages = ['PHP', 'JavaScript', 'Haskell'];

let result = => item + "!"); 

console.log(result); // ['PHP!', 'JavaScript!', 'Haskell!']

findIndex() method

This method returns the index of the first array element that satisfies the provided test function or else returns -1.

const numbers = [80, 96, 52, 14];

const result = numbers.findIndex(item => item > 90);
console.log(result); // 1 

concat() method

This method returns a new array by merging two or more values/arrays.

const functionalLanguages = ['Haskell', 'PureScript'];
const oopLanguages = ['PHP','C++'];

const languages = functionalLanguages.concat(oopLanguages);

console.log(languages); // ['Haskell', 'PureScript', 'PHP', 'C++']

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

Related Articles

© Copyright 2023 - - All rights reservedVer. 388