Array Methods in JavaScript
Published: 2024-01-13 12:13:20

An array is a special kind of object which contains lists of elements that store multiple values in one place. 
Array Methods are built in functions used for processing or manipulating different types of elements or data values stored in an array. 

Example of an array method:
```
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(value => value * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

```


Now that you have an idea of what an array method is, lets dive deeper and explore the various kinds of array methods available in JavaScript. There are many kinds of array methods in JavaScript and we shall checkout the most commonly used of them all in this tutorial. Also, we shall group them together according to the type of functions they perform for ease of understanding.




### Array method for evaluating length properties.


**length property**: this method is used for checking the number or length of elements in an array, when called the arr.length() method returns a number value equal to the number of elements/items in the array. 

Example:
```

const oddNums = [2, 4, 5, 11, 12];
console.log(oddNums.length); // 5
```





### Array Methods for adding or removing elements.

**push()**: this array method adds one or more elements to the end of an array and returns the new length of the array. The arr.push() method modifies the original array as can be seen below.

Example:

```
let verbs = ["come", "go", "laugh"];
let added = verbs.push("run"); 
console.log(added); // 4
console.log(verbs); // ["come", "go", "laugh", "run"]
```



**pop()**: this array method removes an element from the end of an array and returns the it, this method modifies the original array.

Example:	

```
let nouns = ["house", "cars", "pen", "sun"];
console.log(nouns.pop()); // sun
console.log(nouns); // ["house", "cars", "pen"]

```


**unshift()**: this method adds one or more elements to the beginning of an array and returns its new length. The arr.shift() method modifies the original array.

Example: 

```

let someColors = ["white", "yellow", "purple"];
console.log(someColors.unshift("pink")); // 4 
console.log(someColors); // ["pink", "white", "yellow", "purple"]

```


**shift()**: this array method removes the first element from an array and returns it. Also, this method changes the original array as can be seen below.

Example:

```
let colors = ["red", "blue", "green", "black"];
console.log(colors.shift()); // red
console.log(colors); // ["blue", "green", "black"]

```


**splice()**: this method is used for deleting, inserting, and replacing elements in an array. It accepts two or more arguments.
This syntax arr.splice(start, end) deletes one element starting from index 1 and returns it.

Example: 

```
// Delete 1 item, starting from index 1
 Let items = ["pen", "book", "phone", "cup", "cap"];
 console.log(items.splice(1,1)); // ["book"]
 console.log(items); // ["pen", "phone", "cup", "cap"]

```

```
let removed = items.splice(0, 2); // removes the first two items starting from index 0 and returns them
 console.log(removed); // ["pen", "phone"]
 console.log(items); // ["cup", "cap"]
 console.log(items.length); //2

```

```
// insert items
let add = ["pen", "book", "phone", "phone", "peg"];
 console.log(add.splice(2, 0, "pot", "spoon")); 
 console.log(add); // ["pen", "book", "pot", "spoon", "phone", "phone", "peg"]
 console.log(add.length); // 7
 console.log(add.splice(2, 2, "ball", "glasses")); // ["pot", "spoon"]
 console.log(add); //  ["pen", "book", "ball", "glasses", "phone", "phone", "peg"]
 

```

The above examples show the different ways in which new elements can be deleted, inserted or replaced in an array using the splice() method.


**slice()**: The slice() method takes two arguments like this arr.slice([start], [end]) and returns a new array with a copy of all elements from the start index to the end, without including the end index itself.

Example:

```
let pureItems = ["pen", "book", "phone", "cup", "cap"];
console.log( pureItems.slice(1, 3)); // ["book", "phone"]

let itemNums = [1, 2, 3, 4, 5]
console.log(itemNums.slice(-3)); // [3, 4, 5]


```
 As can be seen from the above example, passing a negative value as argument counts from the ending of the array(from right to left).







### Array methods for finding elements.

**indexOf()**: this array method returns the first index of a specified value or -1 if the value is not found in the array.

Example:

```
let str = "Good Morning Uche";
let index = str.indexOf('Uche');
console.log(index); //13
console.log(str.indexOf('he'); //15

```
 Please note that spaces are counted as well.


**includes()**: this array method checks if an element is included in an array and returns a Boolean value of true if found, otherwise it returns false.

Example:

```
const numArray = [1, 2, 3, 4, 5];
console.log(numArray.includes(5)); // true
console.log(numArray.includes(8)); // false

```


**find()**: this method searches for an element with a matching value in an array and returns the value if found, otherwise, it returns undefined.

Example:

```
const fewNums = [1, 2, 3, 4]
console.log(fewNums.find( num => num == 3 )); // 3

console.log(fewNums.find( num => num == 20 )); // undefined

```


**findIndex()**: this method looks for an element and returns the index where the element was found instead of the element itself. The value of -1 is returned if nothing is found. 

Example:

```
const nums = [9, 5, 4, 6, 8, 9, 12];

let numsIndex = nums.findIndex( num => num === 4);
console.log(numsIndex); // 2

```






### High-order methods

**map()**: this array method transforms array elements by performing an assigned function on each element of the array then returns a new modified array.

Example:

```
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(value => value * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

```


**filter()**: this method returns an array of all matching elements in an array. In order words, it filters off all other elements which did not  pass the test and returns a new array of the filtered elements.

Example:

```
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
console.log(array.filter(num => num > 3 && num <= 8)); // [4, 5, 6, 7, 8]

```


**reduce()**: this array method reduces elements of an array to a single value and returns the value. It accepts the accumulator and current value as arguments.

Example:

```
const gameLevels = [1, 2, 3, 4];
console.log(gameLevels.reduce((acc, curr) => acc + curr)); // 10

```


**some()**: this array method checks if at least one element in an array meets a requirement. This method returns a Boolean value of true when found and false when not found. 

Example:

```
const prices = [30, 210, 180, 20];
console.log(prices.some(price => price > 500)); // false
console.log(prices.some(price => price > 100)); // true

```


**sort()**: this method sorts elements of an array and returns a modified array of sorted elements in an ascending or descending order. In order to return a correctly sorted array, an arrow function like this should be passed to it: (a,b) => a – b;// for sorting in ascending order, or this: (a,b) => b – a; for sorting in descending order. This way it returns a correctly sorted array. 
The reason for this twist is because the elements of an array is first converted to strings for comparison and then sorted out using lexicographic ordering, this makes a number like 3, 4, 5 etc, greater than 12, 22, 10, because the first numbers of each digit are compared and returned. As a result of this, the output differs from the expected output hence, we employ the services of the above arrow function to correct this. 

Example:

```
let evenNums = [2, 8, 16, 4, 24, 6];
console.log(evenNums.sort()); // [16, 2, 24, 4, 6, 8]
console.log(evenNums.sort((a,b) => a - b)); // [2, 4, 6, 8, 16, 24]
console.log(evenNums.sort((a,b) => b - a)); // [24, 16, 8, 6, 4, 2]

```


**every()**: method checks if every element in an array passes a test or satisfies a given requirement.

Example:

```
const ages = [3, 10, 14, 16];
console.log(ages.every(age => age > 2)); // true
console.log(ages.every(age => age > 40)); // false

```


**forEach()**: this method loops through array elements and performs any assigned functions on each item or element in the array.

Example:

```
const primeNums = [1, 2, 3, 5];
primeNums.forEach((item) => console.log(item)); // prints each array items to the console

```





### Concat Method 

**concat()**: this method takes any number of arrays as arguments and returns a new array with all the elements in the previous arrays, then merges them all together.  The syntax is like this: 
arr.concat(arg1, arg2, arg3...)

Example:

```
const alpha = ['a', 'b', 'c'];
const numeric = [1, 2, 3];
const alphaNumeric = alpha.concat(numeric);
console.log(alphaNumeric); // ['a', 'b', 'c', 1, 2, 3]

```





### Reverse Method 

**reverse()**: This method reverses the order of elements in an array.

Example:

```
add = ["pen", "book", "phone", "phone", "peg"];
 console.log(add.reverse()); // ["peg", "phone", "phone", "book", "pen"]

```






### Methods for flattening arrays

**flat()**: this array method flattens an array recursively up to a specified depth.

Example:

```
const freshNums = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
console.log(freshNums.flat(1)); // [1, 2, 3, 4, [5, 6, [7, 8, [9, 10]]]]
console.log(freshNums.flat(2)); // [1, 2, 3, 4, 5, 6, [7, 8, [9, 10]]]
console.log(freshNums.flat(4)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

```

**flatMap()**: this method executes a mapping function on every element in an array and creates a new flat array without changing the original array. 

Example:

```
const arrays = [[1], [2], [3], [4], [5]];
const a = arrays.flatMap(arr => arr * 5);
const b = arrays.flat().map(arr => arr * 10);
console.log(a); // [5, 10, 15, 20, 25]
console.log(b); // [10, 20, 30, 40, 50]

```






### Array to String Method

**join()**: this method concatenate all elements of an array into a string separated by a separator and returns an array as a string. This method does not change the original array.

Examples:

```
let letters = ["a", "b", "c"];
console.log(letters.join(',')); // a,b,c
console.log(letters.join('-')); // a-b-c
console.log(letters.join('')); // abc

```



**toString()**: this method converts each element of the array into a string and concatenates them together, separated by a comma.

Examples:

```
let favNums = [1, 2, 3, 4, 5, 8, 13, 22 ];
let convertedNums = favNums.toString();
console.log(convertedNums); // 1,2,3,4,5,8,13,22
console.log(typeof(convertedNums)); // string

```



**concatenation(+)**: this method converts an array to a string through a method called implicit coercion. In order words, JavaScript implicitly coerces the array to a string using the concatenation operator +.

Examples:

```
let got = "" + favNums
console.log(got); // 1,2,3,4,5,8,13,22
console.log(typeof(got)); // string

```



**string()**: an array can also be explicitly coerced to string using a String constructor.

Examples:

```
let bigNums = [58, 96, 68, 87];
let convertedBigNums = String(bigNums);
console.log(convertedBigNums); // 58,96,68,87
console.log(typeof(convertedBigNums)); // string

```


### In Conclusion:
Now that you have learnt about the various methods of accessing, modifying and manipulating elements stored in arrays, you now understand why array methods are so important in JavaScript. It is equally important to understand and consider best practices when choosing an appropriate method for solving a particular problem while working with arrays.
Hope you enjoyed reading this far, thanks for reading.