DEV Community

Cover image for Summary of Common Javascript Array Methods
Snowie Wong
Snowie Wong

Posted on

Summary of Common Javascript Array Methods

Here's a summary on common JavaScript Array methods:

List of common JavaScript Array Methods

1) length

Return the length / size of an array

const pets = ['cat', 'dog'];
console.log(pets.length);  // Output: 2
Enter fullscreen mode Exit fullscreen mode

2) push() & pop()

push(): Adds one or more elements to the end of an array

const pets = ['cat', 'dog'];
pets.push('hamster');
console.log(pets);   // Output: ['cat', 'dog', 'hamster']

pets.push('bunny', 'parrot');
console.log(pets);  
// Output: ['cat', 'dog', 'hamster', 'bunny', 'parrot']
Enter fullscreen mode Exit fullscreen mode

pop(): Removes the last element from an array and returns that element

const pets = ['cat', 'dog', 'hamster'];
const lastElement = pets.pop();

console.log(lastElement);   // Output: 'hamster'
console.log(pets);   // Output: ['cat', "dog']
Enter fullscreen mode Exit fullscreen mode

3) shift() & unshift()

shift(): Removes the first element from an array and returns that element

const pets = ['cat', 'dog', 'hamster'];
const firstElement = pets.shift();

console.log(firstElement);  // Output: 'cat'
console.log(pets);  // Output: ['dog', 'hamster']
Enter fullscreen mode Exit fullscreen mode

unshift(): Adds one or more elements to the beginning of an array & return a new length of an array

const pets = ['cat', 'dog'];
pets.unshift('bunny', 'lizard');
console.log(pets);   
// Output: ['bunny', 'lizard', 'cat', 'dog']

let newArrayLength = pets.unshift('parrot');
console.log(pets);   
// Output: ['parrot', 'bunny', 'lizard', 'cat', 'dog']
console.log(newArrayLength);   // Output: 5
Enter fullscreen mode Exit fullscreen mode

4) slice() & splice()

slice(): Returns a shallow copy of a portion of an array selected from start index to end index (end index item not included), without modifying the original array

slice(startIndex, endIndex):

const pets = ['cat', 'dog', 'hamster', 'bunny', 'lizard'];
let result1 = pets.slice(2);
console.log(result1);  
// Output: ['hamster', 'bunny', 'lizard']

let result2 = pets.slice(2, 4);
console.log(result2);   
// Output: ['hamster', 'bunny']

let result3 = pets.slice(-3);
console.log(result3);   
// Output: ['hamster', bunny', 'lizard']

let result4 = pets.slice();
console.log(result4);   
// Output: ['cat', 'dog', 'hamster', 'bunny', 'lizard']
Enter fullscreen mode Exit fullscreen mode

splice(): Changes the contents of an array by removing, replacing, or adding elements. It modifies the original array

splice(index, deleteCount, item):

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');   // insert at index 1
console.log(months);   
// Output: ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');   // replace 1 element at index 4
console.log(months);   
// Output: ['Jan', 'Feb', 'March', 'April', 'May']
Enter fullscreen mode Exit fullscreen mode

5) join()

Joins all elements of an array into a string

const elements = ['heat', 'oxygen', 'fuel'];
console.log(elements.join()); // Output: "heat,oxygen,fuel"
Enter fullscreen mode Exit fullscreen mode

6) .concat() or ... Spread Operator

.concat() or ...: Combine arrays together into one array

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr1 = arr1.concat(arr2);
console.log(combinedArr1);
// Output: [1,2,3,4,5,6]

const combinedArr2 = [...arr1, ...arr2];  // more flexible
console.log(combinedArr2);
// Output: [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

6) indexOf() & includes()

indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it's not present

const pokemons = ['pikachu', 'squirtle', 'bulbasaur'];
console.log(pokemons.indexOf('squirtle'));   // Output: 1
console.log(pokemons.indexOf('charmander'));   // Output: -1
Enter fullscreen mode Exit fullscreen mode

includes(): Determines whether an array includes a certain element, returning true or false as appropriate

const myWeekendPlan = ['sleep', 'video games', 'anime', 'unhealthy food'];
console.log(myWeekendPlan.includes('anime'));   // Output: true
console.log(myWeekendPlan.includes('work'));   // Output: false
Enter fullscreen mode Exit fullscreen mode

7) forEach()

Executes a provided function once for each array element

const array1 = ['hehe', 'haha', 'hoho'];
array1.forEach((element) => console.log(element));

Output:
'hehe'
'haha'
'hoho'
Enter fullscreen mode Exit fullscreen mode

8) filter()

Creates a new array with all elements that pass the test provided by a provided function

const words = ['good', 'nice', 'great', 'amazing', 'cool', 'awesome'];
const result = words.filter((word) => word.length > 6);
console.log(result);   // Output: ['amazing', 'awesome']
Enter fullscreen mode Exit fullscreen mode

9) map()

Creates a new array by calling a provided function on each element of the original array

const array1 = [1, 2, 3, 4];
const map1 = array1.map((x) => x * x);
console.log(map1);   // Output: [1, 4, 9, 16]

const cart = [5, 15, 25];
const cartWithTax = cart.map((cost) => cost * 1.2);
console.log(cartWithTax);   // Output: [6, 18, 30]
Enter fullscreen mode Exit fullscreen mode

10) reduce()

Applies a function to reduce the array to a single value (from left-to-right)

const cart = [5, 15, 25];
const cartTotal = cart.reduce((total, itemPrice) => total + itemPrice, 0);  // 0 = initial value of total
console.log(cartTotal);   // Output: 45
Enter fullscreen mode Exit fullscreen mode

11) sort()

Sorts the elements of an array in place and returns the sorted array

If comparison function is not provided, sort converts elements to strings & sorts them based on their UTF-16 code units (may not fit in most use case, so we usually use it with a comparison function)

const months = ['March', 'Jan', 'Feb', 'Dec'];
console.log(months.sort());   
// Output: ['Dec', 'Feb', 'Jan', 'March']

const numbers = [30, 11, 110, 5, 20, 41];
console.log(numbers.sort());
// Output: [11, 110, 20, 30, 41, 5]  <- doesn't get sorted by numeric value
Enter fullscreen mode Exit fullscreen mode

When comparison function is provided & it returns a negative number, it indicates the first element should come before the second element. If it returns a positive number, it indicates that the first element should come after the second element in the sorted order. If it returns 0, the elements are considered as equal & their order remains unchanged

const numbers = [3, 1, 5, 2, 4];
numbers.sort((a, b) => a - b);  // from small to large
console.log(numbers);   
// Output: [1, 2, 3, 4, 5]

const names = ['alan', 'may', 'alice', 'ben', 'john' , 'catie'];
names.sort((a, b) => a.localeCompare(b));  // sort names alphabetically
console.log(names);   
// Output: ["alan", "alice", "ben", "catie", "john", "may"]
Enter fullscreen mode Exit fullscreen mode

12) find() & findIndex()

find(): Returns the first element in the array that satisfies the provided function

const numbersArray = [3, 99, 108, 87, 65, 110];
const foundNumber = numbersArray.find((element) => element > 100);
console.log(foundNumber);    // Output: 108
Enter fullscreen mode Exit fullscreen mode

findIndex(): Returns the index of the first element in the array that satisfies the provided function

const numbersArray = [10, 20, 30, 40, 50];
const foundIndex = numbersArray.findIndex((number) => number > 25);
console.log(foundIndex);    // Output: 2
Enter fullscreen mode Exit fullscreen mode

13) some()

Check if at least one element in an array satisfies a specified condition, returns true if any element passes the condition

const products = [
  { name: 'Smartphone', price: 500 },
  { name: 'Laptop', price: 1000 },
  { name: 'Microphone', price: 30 },
  { name: 'Headset', price: 50 },
];
const priceMaxLimit = 100;
const hasItemsInPriceRange = products.some(product => product.price <= priceMaxLimit);
console.log(hasItemsInPriceRange);  // Output: true
Enter fullscreen mode Exit fullscreen mode

14) every()

Check if all elements in an array satisfy a specified condition, returns true only if all elements pass the condition.

const surveyQuestions = [
  { question: 'Question 1', answer: 'Yes' },
  { question: 'Question 2', answer: 'No' },
  { question: 'Question 3', answer: '' },    // unanswered
];
const isSurveyComplete = surveyQuestions.every(question => question.answer);   
console.log(isSurveyComplete)   // Output: false
Enter fullscreen mode Exit fullscreen mode

That's all and hope that it helps! I always find myself googling some methods again & again so decided to write this & help me memorize it better lol

Reference: Mozilla's web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Top comments (0)