JavaScript Array Methods
JavaScript Array Methods
Section titled “JavaScript Array Methods”JavaScript arrays come with a rich set of built-in methods to perform common operations like adding/removing elements, iteration, transformation, and more. Understanding these methods is key to effective JavaScript programming.
Converting Arrays to Strings
Section titled “Converting Arrays to Strings”The toString() method converts an array to a comma-separated string of its elements.
const fruits = ["Banana", "Orange", "Apple", "Mango"];console.log(fruits.toString()); // Output: "Banana,Orange,Apple,Mango"The join() method also joins all array elements into a string, but allows you to specify a separator.
const fruits = ["Banana", "Orange", "Apple", "Mango"];console.log(fruits.join(" * ")); // Output: "Banana * Orange * Apple * Mango"console.log(fruits.join(" - ")); // Output: "Banana - Orange - Apple - Mango"Adding and Removing Elements (Mutating Methods)
Section titled “Adding and Removing Elements (Mutating Methods)”These methods modify the original array.
pop(): Removes the last element from an array and returns that element.
const fruits = ["Banana", "Orange", "Apple", "Mango"];const lastFruit = fruits.pop();console.log(lastFruit); // Output: "Mango"console.log(fruits); // Output: ["Banana", "Orange", "Apple"]push(): Adds one or more new elements to the end of an array and returns the new length of the array.
const fruits = ["Banana", "Orange", "Apple"];const newLength = fruits.push("Kiwi", "Lemon");console.log(newLength); // Output: 5console.log(fruits); // Output: ["Banana", "Orange", "Apple", "Kiwi", "Lemon"]shift(): Removes the first element from an array and returns that element. This operation shifts all subsequent elements to a lower index.
const fruits = ["Banana", "Orange", "Apple"];const firstFruit = fruits.shift();console.log(firstFruit); // Output: "Banana"console.log(fruits); // Output: ["Orange", "Apple"]unshift(): Adds one or more new elements to the beginning of an array and returns the new length of the array. This operation shifts existing elements to higher indices.
const fruits = ["Orange", "Apple"];const newLengthUnshift = fruits.unshift("Lemon", "Pineapple");console.log(newLengthUnshift); // Output: 4console.log(fruits); // Output: ["Lemon", "Pineapple", "Orange", "Apple"]splice(): A powerful method to change the contents of an array by removing or replacing existing elements and/or adding new elements in place. It returns an array containing the deleted elements.
Syntax: array.splice(startIndex, deleteCount, item1, item2, ...)
const fruits = ["Banana", "Orange", "Apple", "Mango"];// Add elements: At index 2, remove 0 elements, add "Lemon", "Kiwi"fruits.splice(2, 0, "Lemon", "Kiwi");console.log(fruits); // Output: ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]
// Remove elements: At index 0, remove 1 elementconst removed = fruits.splice(0, 1);console.log(removed); // Output: ["Banana"]console.log(fruits); // Output: ["Orange", "Lemon", "Kiwi", "Apple", "Mango"]
// Replace elements: At index 1, remove 2 elements, add "Grape"fruits.splice(1, 2, "Grape");console.log(fruits); // Output: ["Orange", "Grape", "Apple", "Mango"]Note: Using delete array[index] creates undefined holes in the array. It’s generally better to use splice(), pop(), or shift() for removing elements.
Creating New Arrays from Existing Ones (Non-Mutating Methods)
Section titled “Creating New Arrays from Existing Ones (Non-Mutating Methods)”These methods return a new array and do not modify the original.
concat(): Merges two or more arrays (or values) to create a new array.
const arr1 = ["Cecilie", "Lone"];const arr2 = ["Emil", "Tobias"];const arr3 = ["Robin"];const children = arr1.concat(arr2, arr3, "Peter");console.log(children); // Output: ["Cecilie", "Lone", "Emil", "Tobias", "Robin", "Peter"]console.log(arr1); // Output: ["Cecilie", "Lone"] (original unchanged)Using the spread syntax (...) is a modern alternative for concatenation:
const newChildren = [...arr1, ...arr2, ...arr3, "Peter"];console.log(newChildren);slice(): Extracts a section of an array and returns a new array. The original array is not modified.
Syntax: array.slice(startIndex, endIndex) (endIndex is exclusive)
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];const citrus = fruits.slice(1, 3); // Elements from index 1 up to (but not including) index 3console.log(citrus); // Output: ["Orange", "Lemon"]
const endFruits = fruits.slice(2); // Elements from index 2 to the endconsole.log(endFruits); // Output: ["Lemon", "Apple", "Mango"]
const shallowCopy = fruits.slice(); // Creates a shallow copy of the arrayconsole.log(shallowCopy);The spread syntax (...) is also commonly used for shallow copying arrays:
const spreadCopy = [...fruits];console.log(spreadCopy);Sorting Arrays
Section titled “Sorting Arrays”sort(): Sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings (lexicographically).
const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.sort();console.log(fruits); // Output: ["Apple", "Banana", "Mango", "Orange"]
const numbers = [40, 100, 1, 5, 25, 10];numbers.sort(); // Incorrect numeric sort!console.log(numbers); // Output: [1, 10, 100, 25, 40, 5] (sorted as strings)Numeric Sort: To sort numbers correctly, you must provide a compare function.
const points = [40, 100, 1, 5, 25, 10];// Ascending orderpoints.sort(function(a, b) { return a - b; });// Using arrow function: points.sort((a, b) => a - b);console.log(points); // Output: [1, 5, 10, 25, 40, 100]
// Descending orderpoints.sort(function(a, b) { return b - a; });// Using arrow function: points.sort((a, b) => b - a);console.log(points); // Output: [100, 40, 25, 10, 5, 1]The compare function (a, b) should return: a negative value if a should come before b, a positive value if a should come after b, or zero if their order doesn’t matter.
reverse(): Reverses the order of the elements in an array in place and returns the reversed array.
const fruits = ["Banana", "Orange", "Apple"];fruits.reverse();console.log(fruits); // Output: ["Apple", "Orange", "Banana"]Modern Iteration and Transformation Methods (ES5+)
Section titled “Modern Iteration and Transformation Methods (ES5+)”These methods are generally preferred over manual for loops for their conciseness and expressiveness. They do not mutate the original array unless specified (like forEach callback could).
forEach(callbackFn): Executes a provided function once for each array element.
const numbers = [1, 2, 3];numbers.forEach(function(number, index, array) { console.log(`Element at index ${index}: ${number}`);});map(callbackFn): Creates a new array populated with the results of calling a provided function on every element in the calling array.
const numbers = [1, 4, 9];const roots = numbers.map(function(num) { return Math.sqrt(num);});// Using arrow function: const roots = numbers.map(num => Math.sqrt(num));console.log(roots); // Output: [1, 2, 3]filter(callbackFn): Creates a new array with all elements that pass the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5, 6];const evens = numbers.filter(function(num) { return num % 2 === 0;});// Using arrow function: const evens = numbers.filter(num => num % 2 === 0);console.log(evens); // Output: [2, 4, 6]reduce(callbackFn, initialValue): Executes a reducer function on each element of the array, resulting in a single output value.
const numbers = [1, 2, 3, 4];const sum = numbers.reduce(function(accumulator, currentValue) { return accumulator + currentValue;}, 0); // 0 is the initialValue for accumulator// Using arrow function: const sum = numbers.reduce((acc, val) => acc + val, 0);console.log(sum); // Output: 10find(callbackFn): Returns the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
const numbers = [10, 20, 35, 40];const found = numbers.find(num => num > 30);console.log(found); // Output: 35findIndex(callbackFn): Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
const numbers = [10, 20, 35, 40];const foundIndex = numbers.findIndex(num => num > 30);console.log(foundIndex); // Output: 2some(callbackFn): Tests whether at least one element in the array passes the test implemented by the provided function. Returns a boolean.
const numbers = [1, 3, 5, 7, 8];const hasEven = numbers.some(num => num % 2 === 0);console.log(hasEven); // Output: trueevery(callbackFn): Tests whether all elements in the array pass the test implemented by the provided function. Returns a boolean.
const numbers = [2, 4, 6, 8];const allEven = numbers.every(num => num % 2 === 0);console.log(allEven); // Output: trueincludes(valueToFind, fromIndex): Determines whether an array includes a certain value among its entries, returning true or false.
const pets = ['cat', 'dog', 'bat'];console.log(pets.includes('cat')); // Output: trueconsole.log(pets.includes('at')); // Output: false (checks for whole element)console.log(pets.includes('dog', 1)); // Output: true (starts search from index 1)Other Useful Methods (ES6+)
Section titled “Other Useful Methods (ES6+)”Array.from(arrayLikeOrIterable): Creates a new, shallow-copied Array instance from an array-like or iterable object.
const str = "hello";const chars = Array.from(str);console.log(chars); // Output: ['h', 'e', 'l', 'l', 'o']
function getArgs() { return Array.from(arguments);}console.log(getArgs(1, 'a', true)); // Output: [1, 'a', true]flat(depth): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
const arr = [1, [2, [3, 4]], 5];console.log(arr.flat()); // Output: [1, 2, [3, 4], 5] (depth 1)console.log(arr.flat(2)); // Output: [1, 2, 3, 4, 5]console.log(arr.flat(Infinity)); // Output: [1, 2, 3, 4, 5]flatMap(callbackFn): First maps each element using a mapping function, then flattens the result into a new array. It is identical to a.map(...args).flat(), but slightly more efficient.
const arr = [1, 2, 3];const result = arr.flatMap(x => [x, x * 2]);console.log(result); // Output: [1, 2, 2, 4, 3, 6]Finding Max/Min in an Array
Section titled “Finding Max/Min in an Array”While sort() can be used, it’s not the most efficient way to find the single highest or lowest value. Use Math.max() or Math.min() with the spread syntax, or reduce().
const points = [40, 100, 1, 5, 25, 10];
// Using Math.max/min with spread operatorconst highest = Math.max(...points);const lowest = Math.min(...points);console.log(`Highest: ${highest}, Lowest: ${lowest}`); // Highest: 100, Lowest: 1
// Using reduceconst highestReduce = points.reduce((max, current) => Math.max(max, current), -Infinity);const lowestReduce = points.reduce((min, current) => Math.min(min, current), Infinity);console.log(`Highest (reduce): ${highestReduce}, Lowest (reduce): ${lowestReduce}`);Complete Array Reference
Section titled “Complete Array Reference”JavaScript arrays have many more methods. For a complete reference, including detailed descriptions, syntax, and examples of all Array properties and methods, consult the MDN Web Docs for the JavaScript Array object.