Summary of Common Javascript Array Methods
Tags: javascript, webdev, beginners, programming
Published: 2023-10-24 10:07:54

Here's a summary on common JavaScript Array methods:

![List of common JavaScript Array Methods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7mpjb1n0zalcx8tsd7t.png)

## 1) length

Return the length / size of an array

```js
const pets = ['cat', 'dog'];
console.log(pets.length);  // Output: 2
```

## 2) push() & pop()
`push()`: Adds one or more elements to the end of an array 
```js
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']
```

`pop()`: Removes the last element from an array and returns that element
```js
const pets = ['cat', 'dog', 'hamster'];
const lastElement = pets.pop();

console.log(lastElement);   // Output: 'hamster'
console.log(pets);   // Output: ['cat', "dog']
```

## 3) shift() & unshift()
`shift()`: Removes the first element from an array and returns that element
```js
const pets = ['cat', 'dog', 'hamster'];
const firstElement = pets.shift();

console.log(firstElement);  // Output: 'cat'
console.log(pets);  // Output: ['dog', 'hamster']
```

`unshift()`: Adds one or more elements to the beginning of an array & return a new length of an array
```js
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
```

## 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)`:
```js
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']
```

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

`splice(index, deleteCount, item)`:
```js
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']
```

## 5) join()
Joins all elements of an array into a string
```js
const elements = ['heat', 'oxygen', 'fuel'];
console.log(elements.join()); // Output: "heat,oxygen,fuel"
```

## 6) .concat() or ... Spread Operator 
`.concat()` or `...`: Combine arrays together into one array
```js
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]
```

## 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
```js
const pokemons = ['pikachu', 'squirtle', 'bulbasaur'];
console.log(pokemons.indexOf('squirtle'));   // Output: 1
console.log(pokemons.indexOf('charmander'));   // Output: -1
```

`includes()`: Determines whether an array includes a certain element, returning `true` or `false` as appropriate
```js
const myWeekendPlan = ['sleep', 'video games', 'anime', 'unhealthy food'];
console.log(myWeekendPlan.includes('anime'));   // Output: true
console.log(myWeekendPlan.includes('work'));   // Output: false
```

## 7) forEach()
Executes a provided function once for each array element
```js
const array1 = ['hehe', 'haha', 'hoho'];
array1.forEach((element) => console.log(element));

Output:
'hehe'
'haha'
'hoho'
```

## 8) filter()
Creates a new array with all elements that pass the test provided by a provided function
```js
const words = ['good', 'nice', 'great', 'amazing', 'cool', 'awesome'];
const result = words.filter((word) => word.length > 6);
console.log(result);   // Output: ['amazing', 'awesome']
```

## 9) map()
Creates a new array by calling a provided function on each element of the original array
```js
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]
```

## 10) reduce()
Applies a function to reduce the array to a single value (from left-to-right)
```js
const cart = [5, 15, 25];
const cartTotal = cart.reduce((total, itemPrice) => total + itemPrice, 0);  // 0 = initial value of total
console.log(cartTotal);   // Output: 45
```

## 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)
```js
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
```

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
```js
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"]
```

## 12) find() & findIndex()
`find()`: Returns the `first element` in the array that satisfies the provided function
```js
const numbersArray = [3, 99, 108, 87, 65, 110];
const foundNumber = numbersArray.find((element) => element > 100);
console.log(foundNumber);    // Output: 108
```

`findIndex()`: Returns the index of the `first element` in the array that satisfies the provided function
```js
const numbersArray = [10, 20, 30, 40, 50];
const foundIndex = numbersArray.findIndex((number) => number > 25);
console.log(foundIndex);    // Output: 2
```

## 13) some()
Check if `at least one element` in an array satisfies a specified condition, returns `true` if any element passes the condition
```js
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
```


## 14) every()
Check if `all elements` in an array satisfy a specified condition, returns `true` only if all elements pass the condition. 
```js
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
```

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