Skip to main content

How to use array methods in Javascript?

Mastering array methods in JavaScript is essential for writing clean, efficient code. Here's a guide to the most commonly used methods:

Adding and Removing Elements

push

Array.prototype.push() Add one or more elements to the end of an array and return the new length.

javascript
const jottupFruits = ['apple', 'banana'];
const newLength = jottupFruits.push('cherry');
console.log(jottupFruits); // Expected output: ['apple', 'banana', 'cherry']
console.log(newLength);    // Expected output: 3

pop

Array.prototype.pop() Remove the last element from an array and return that element.

javascript
const jottupColors = ['red', 'green', 'blue'];
const removedColor = jottupColors.pop();
console.log(jottupColors);    // Expected output: ['red', 'green']
console.log(removedColor);    // Expected output: 'blue'

shift

Array.prototype.shift() Remove the first element from an array and return that element.

javascript
const jottupAnimals = ['cat', 'dog', 'bird'];
const firstAnimal = jottupAnimals.shift();
console.log(jottupAnimals);  // Expected output: ['dog', 'bird']
console.log(firstAnimal);    // Expected output: 'cat'

unshift

Array.prototype.unshift() Add one or more elements to the front of an array and return the new length.

javascript
const jottupCars = ['Toyota', 'Honda'];
const carsCount = jottupCars.unshift('Tesla');
console.log(jottupCars); // Expected output: ['Tesla', 'Toyota', 'Honda']
console.log(carsCount);  // Expected output: 3

concat

Array.prototype.concat() Combine two or more arrays.

javascript
const jottupNums1 = [1, 2];
const jottupNums2 = [3, 4];
const mergedNums = jottupNums1.concat(jottupNums2);
console.log(mergedNums); // Expected output: [1, 2, 3, 4]

join

Array.prototype.join() Join all elements of an array into a string.

javascript
const jottupWords = ['Hello', 'World'];
const sentence = jottupWords.join(' ');
console.log(sentence);  // Expected output: 'Hello World'

slice

Array.prototype.slice() Extract a section of an array and return a new array.

javascript
const jottupColors = ['red', 'blue', 'green', 'yellow', 'purple'];
const slicedColors = jottupColors.slice(1, 4);
console.log(slicedColors); // Expected output: ['blue', 'green', 'yellow']

splice

Array.prototype.splice() Change the content of an array by removing or replacing existing elements and/or adding new elements.

javascript
const jottupFruits = ['apple', 'banana', 'cherry', 'date'];
jottupFruits.splice(2, 0, 'blackberry');
console.log(jottupFruits); // Expected output: ['apple', 'banana', 'blackberry', 'cherry', 'date']

forEach

Array.prototype.forEach() Execute a provided function once for each array element.

javascript
const jottupNumbers = [1, 2, 3];
jottupNumbers.forEach(num => {
    console.log(num * 2);
});
// Expected output: 2
// Expected output: 4
// Expected output: 6

map

Array.prototype.map() Create a new array with the results of calling a provided function on every element.

javascript
const jottupTasks = ['cook', 'clean', 'write'];
const updatedTasks = jottupTasks.map(task => `I will ${task}`);
console.log(updatedTasks); // Expected output: ['I will cook', 'I will clean', 'I will write']

filter

Array.prototype.filter() Create a new array with all elements that pass the test implemented by the provided function.

javascript
const jottupAges = [16, 21, 18, 40, 14];
const adults = jottupAges.filter(age => age >= 18);
console.log(adults); // Expected output: [21, 18, 40]

reduce

Array.prototype.reduce() Apply a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

javascript
const jottupPrices = [5, 10, 15];
const totalPrice = jottupPrices.reduce((total, price) => total + price, 0);
console.log(totalPrice); // Expected output: 30

reduceRight

Array.prototype.reduceRight() Apply a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

javascript
const jottupValues = ['a', 'b', 'c'];
const combined = jottupValues.reduceRight((acc, value) => acc + value, '');
console.log(combined); // Expected output: 'cba'

some

Array.prototype.some() Test whether at least one element in the array passes the test implemented by the provided function.

javascript
const jottupScores = [45, 89, 66, 53, 99];
const hasPassed = jottupScores.some(score => score >= 90);
console.log(hasPassed); // Expected output: true

every

Array.prototype.every() Test whether all elements in the array pass the test implemented by the provided function.

javascript
const jottupAges = [25, 30, 29, 24, 31];
const allAdults = jottupAges.every(age => age >= 18);
console.log(allAdults); // Expected output: true

find

Array.prototype.find() Return the first element in the array that satisfies the provided testing function.

javascript
const jottupPrices = [50, 30, 70, 40];
const priceyItem = jottupPrices.find(price => price > 60);
console.log(priceyItem); // Expected output: 70

findIndex

Array.prototype.findIndex() Return the index of the first element in the array that satisfies the provided testing function.

javascript
const jottupProducts = ['apple', 'banana', 'cherry'];
const cherryIndex = jottupProducts.findIndex(product => product === 'cherry');
console.log(cherryIndex); // Expected output: 2

indexOf

Array.prototype.indexOf() Return the first index at which a certain element can be found in the array, or -1 if the element is not found.

javascript
const jottupAnimals = ['cat', 'dog', 'fish', 'cat'];
const firstCatIndex = jottupAnimals.indexOf('cat');
console.log(firstCatIndex); // Expected output: 0

lastIndexOf

Array.prototype.lastIndexOf() Return the last index at which a certain element can be found in the array, or -1 if the element is not found.

javascript
const lastCatIndex = jottupAnimals.lastIndexOf('cat');
console.log(lastCatIndex); // Expected output: 3

includes

Array.prototype.includes() Determine whether an array includes a certain element.

javascript
const hasDog = jottupAnimals.includes('dog');
console.log(hasDog); // Expected output: true

fill

Array.prototype.fill() Fill all the elements in an array from a start index to an end index with a static value.

javascript
const jottupNumbers = [1, 2, 3, 4, 5];
jottupNumbers.fill(0, 1, 4);
console.log(jottupNumbers); // Expected output: [1, 0, 0, 0, 5]

sort

Array.prototype.sort() Sort the elements of an array in place and return the array.

javascript
const jottupLetters = ['d', 'a', 'c', 'b'];
jottupLetters.sort();
console.log(jottupLetters); // Expected output: ['a', 'b', 'c', 'd']

reverse

Array.prototype.reverse() Reverse the elements of an array in place.

javascript
const jottupColors = ['red', 'green', 'blue'];
jottupColors.reverse();
console.log(jottupColors); // Expected output: ['blue', 'green', 'red']

toLocaleString

Array.prototype.toLocaleString() Return a localized string representing the elements of the array.

javascript
const jottupNumbers = [1300.4, 2500.5];
console.log(jottupNumbers.toLocaleString('de-DE')); // Expected output: '1.300,4' '2.500,5'

toString

Array.prototype.toString() Return a string representing the specified array and its elements.

javascript
const jottupAnimals = ['cat', 'dog', 'fish'];
console.log(jottupAnimals.toString()); // Expected output: 'cat,dog,fish'

entries

Array.prototype.entries() Return a new Array Iterator object that contains the key/value pairs for each index in the array.

javascript
const jottupEntries = jottupAnimals.entries();
for (const [index, element] of jottupEntries) {
    console.log(index, element);
}
// Expected output: 0 'cat', 1 'dog', 2 'fish'

keys

Array.prototype.keys() Return a new Array Iterator object that contains the keys for each index in the array.

javascript
const jottupKeys = jottupAnimals.keys();
for (const key of jottupKeys) {
    console.log(key);
}
// Expected output: 0, 1, 2

values

Array.prototype.values() Return a new Array Iterator object that contains the values for each index in the array.

javascript
const jottupValues = jottupAnimals.values();
for (const value of jottupValues) {
    console.log(value);
}
// Expected output: 'cat', 'dog', 'fish'

copyWithin

Array.prototype.copyWithin() Shallow copies part of an array to another location in the same array and returns it, without modifying its size.

javascript
const jottupDigits = [1, 2, 3, 4, 5];
jottupDigits.copyWithin(0, 3);
console.log(jottupDigits); // Expected output: [4, 5, 3, 4, 5]

flat

Array.prototype.flat() Return a new array with all sub-array elements concatenated into it recursively up to the specified depth.

javascript
const jottupNested = [1, [2, 3, [4, 5]]];
console.log(jottupNested.flat(2)); // Expected output: [1, 2, 3, 4, 5]

flatMap

Array.prototype.flatMap() First map each element using a mapping function, then flatten the result into a new array.

javascript
const jottupData = [1, 2, 3];
const result = jottupData.flatMap(x => [x, x * 2]);
console.log(result); // Expected output: [1, 2, 2, 4, 3, 6]

This list comprises the core array methods as of ECMAScript 2019 (ES10). However, JavaScript (and the ECMAScript standard it's based on) is constantly evolving, so new methods could be added in future iterations of the language. Always refer to the latest ECMAScript specification or authoritative resources like MDN for the most up-to-date information. If you are new to JavaScript, you may also want to review variables and constants to solidify your fundamentals.

Related Articles