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.
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"
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
This method adds zero or more elements to the end of an array.
let languages = ['PHP', 'JavaScript', 'Haskell'];
.push('PureScript');
languages
console.log(languages); // ["PHP", "JavaScript", "Haskell", "PureScript"];
This method executes a provided function for each array element.
const languages = ['PHP', 'JavaScript', 'Haskell'];
.forEach(language => console.log(language));
languages
// PHP
// JavaScript
// Haskell
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
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']
This method creates a new array with the result of calling a function for every array element.
let languages = ['PHP', 'JavaScript', 'Haskell'];
let result = languages.map(item => item + "!");
console.log(result); // ['PHP!', 'JavaScript!', 'Haskell!']
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
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 X (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.