Javascript array methods with examples and combinations
Tags: javascript, beginners, webdev, tutorial
Published: 2022-02-26 20:27:11

### introduction

javascript `Array` object has great tools and methods that we can make use of to achieve optimal data processing needed in our projects. let's walk through one by one and figure out the mechanics, arguments, return statements, etc

---

### concat()

syntax: `concat(value1,value2,...)`
concatenate two or more arrays and return a new array

```javascript
let arr1 = ['a', 'b', 'c', 'd'];
let arr2 = ['e', 'f', 'g', 'h'];
let newArr = arr1.concat(arr2); //output:['a','b','c','d','e','f','g','h']
let newArr2 = ['i', 'j'].concat(arr1, arr2); //output:['a','b','c','d','e','f','g','h']
```

> 💡Tip: it won't mutate the original array instead return a new one

---

### flat()

syntax:`flat(depth)`

as the name suggests it will flatten the array by given depth meaning the sub-arrays will be concatenating to form a new array, it removes empty slots(no holes in the returning array). specifying infinity as depth would return an array without any sub-arrays. the default depth is 1

```javascript
let arr1 = ['foo', 'bar', ['bear', 'claw'], ['orange', ['onion', 'apple']]];
let arr2 = arr1.flat(); //['foo','bar','bear','claw','orange',['onion','apple']]
let arr3 = arr1.flat(infinity); //['foo','bar','bear','claw','orange','onion','apple']
```

> 💡Tip: it won't mutate the original array instead returns a new one

---

### fill()

syntax:`fill(value,start,end)`

-  start:index number
-  end: index number

this method changes all elements of the array to a static given value from the start index to an end index.it changes the start index and all the elements between the start to the end except the end index. the end index is exclusive

```javascript
let arr1 = [1, 2, 3, 4];
let arr2 = arr1.fill(5); //[5,5,5,5]
let arr3 = arr1.flat(5, 1); //[1,5,5,5]
```

> 💡Tip: it ==will== mutate the original array

---

### copyWithin()

syntax:`copyWithin(target,start,end)`

-  target: index number
-  start : index number( optional , default : 0 )
-  end : index number( optional , default : arr.length ,)

shallow copies part of the array to a different location in the same array with the given start and end index and returns the modified array, it will preserve the array length. remember that the end index is not included

```javascript
let arr1 = ['book', 'chair', 'desk', 'table'];
let arr2 = arr1.copyWithin(1); //['book','book','desk','table']
let arr3 = arr1.copyWithin(2, 1, 3); //['book','chair','chair','desk']
```

> 💡 Tip: it ==will== mutate the original array

we'll talk about what shallow copy is and how to deal with it in different situations later in this article

---

### every()

syntax : `every(callbackfn)`

this method accepts a function as an argument and iterates over every single value in the array and executes the function.`every` checks every value in the array against a comparison function. if all of the callback functions return a truthy value on each element the `every` method result would be `true`

```javascript
let arr1 = [4, 6, 24, 120, 44];
//check if all items are even
let test = arr1.every((value, index, arr) => value % 2 === 0); // output:true
```

> 💡Tip: every returns true for an empty array no matter what the condition is

---

### filter()

syntax : `filter((value,index,arr)=> /* ....*/ )`

`filter` returns a new array consisting of elements that have passed a test by the callback function.

```javascript
let arr1 = [
   { id: 1, product: 'mouse', countInStock: 2 },
   { id: 2, product: 'keyboard', countInStock: 0 },
   { id: 3, product: 'monitor', countInStock: 0 },
   { id: 1, product: 'watch', countInStock: 4 },
];

let arr2 = arr1.filter((el, index) => el.countInStock > 0);
// output:[
//  {id:1,product:'mouse',countInStock:2},
//  {id:1,product:'watch',countInStock:4}
// ]
```

> 💡 Tip: it won't mutate the original array instead returns a new one

---

### find()

syntax : `find((val,index,arr)=>/* ... */)`

`find` method iterator over an array and returns the first item that satisfied the testing function otherwise returns undefined

```javascript
let arr1 = [
   { id: 1, product: 'mouse', countInStock: 2 },
   { id: 2, product: 'keyboard', countInStock: 1 },
   { id: 3, product: 'monitor', countInStock: 4 },
   { id: 1, product: 'watch', countInStock: 4 },
];

let element = arr1.find((item, index) => item.countInStock > 3);
// output:{id:3,product:'monitor',countInStock:4}
```

---

### findIndex()

syntax : `findIndex((item,index)=>/* ... */)`

`findIndex` iterates over the array and returns the ==index== of the first element that satisfies the testing function otherwise this method returns ==-1==.

```javascript
let arr1 = [
   { id: 1, product: 'mouse', countInStock: 2 },
   { id: 2, product: 'keyboard', countInStock: 0 },
   { id: 3, product: 'monitor', countInStock: 4 },
   { id: 1, product: 'watch', countInStock: 4 },
];

let element = arr1.findIndex((item, index) => item.countInStock > 7);
// output: -1
let element = arr1.findIndex((item, index) => item.countInStock > 0);
// output: 0
```

---

### forEach()

syntax : `forEach((item,index)=> /* ... */)`

`forEach()` execute the function that is provided on each element.`forEach` always returns `undefined`.

```javascript
let arr1 = [
   { id: 1, product: 'mouse', countInStock: 2 },
   { id: 2, product: 'keyboard', countInStock: 0 },
   { id: 3, product: 'monitor', countInStock: 4 },
   { id: 1, product: 'watch', countInStock: 4 },
];

let element = arr1.forEach(
   (item, index) => item.product === 'mouse' && item.countInStock--
);
// arr1=[
//	  {id:1,product:'mouse',countInStock:1},
//      {id:2,product:'keyboard',countInStock:0},
//      {id:3,product:'monitor',countInStock:4},
//      {id:1,product:'watch',countInStock:4}
//]
```

there is no way to break out of `forEach` loop

---

### includes()

syntax : `includes(value,fromIndex)`

-  fromIndex : index number (default : 0)
   `includes` determines whether the given value is included in the array if so returns true or else false. we can give a second argument (`formIndex`) to specify an index as a start searching point

```javascript
let arr1 = ['MONEY', 'laptop', 'rug'];
let test = arr1.includes('Money'); // output:false
```

> 💡Tip: `includes` is case sensitive

---

### indexOf()

syntax : `indexOf(value,fromIndex)`

fromIndex -> default : `0`

it's a fairly known method that returns the first index at which the value is located. remember if there are a bunch of items with the same value and you haven't specified the second argument (`fromIndex`), `indexOf` returns the first index.in case `indexOf` couldn't find anything, it would return `-1`. the second argument specifies where `indexOf` should start the search

> `fromIndex` is inclusive

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'rug', 'book', 'laptop'];
let arr2 = arr1.indexOf('MONEy'); // output:-1
let arr3 = arr1.indexOf('laptop', 2); // output:2
let arr4 = arr1.indexOf('laptop', 3); // output:5
```

> 💡`indexOf` is case sensitive

---

### join()

syntax : `join(separator)`

joining array items separated by `,` or the given separator

```javascript
let arr1 = ['2022', '23', '2'];
let str = arr1.join(); // output:2022,23,2
let str = arr1.join('-'); // output:2022-23-2
```

---

### lastIndexOf()

syntax : `lastIndexOf(item,fromIndex)`

fromIndex -> default : `array.length - 1`

it is the same as `indexOf` with a little hint, `lastIndex` search backward meaning that the `fromIndex` default value is `array.length - 1` so any value above array length would return `-1` (not found).

> `fromIndex` is inclusive

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let arr2 = arr1.lastIndexOf('MONEy'); // output:-1
let arr3 = arr1.lastIndexOf('laptop', 3); // output:2 starting at index 3
// searching backwards

let arr4 = arr1.lastIndexOf('laptop', 4); // output:4 fromIndex is inclusive
```

> 💡`indexOf` is case sensitive

---

### map()

syntax : `map((item,index,array)=> /* ... */)`

a method to iterate over an array and perform a callback function on each item and return a ==new== array with the values provided by the callback function and the same length as the original array.it is one of the most used methods, especially in javascript frameworks and libraries (e.g React,..).

```javascript
// order list
let arr1 = [
   { id: 1, product: 'mouse', quantity: 2, price: 40 },
   { id: 2, product: 'keyboard', quantity: 0, price: 150 },
   { id: 3, product: 'monitor', quantity: 4, price: 500 },
   { id: 1, product: 'watch', quantity: 4, price: 1000 },
];

let arr2 = arr1.map(({ product, quantity, price }) => ({
   product,
   total: quantity * price,
}));
// output:[
// {product:'mouse',total:80 },
//  {product:'keyboard',total:300},
//  {product:'monitor',total:2000},
//  {product:'watch',total:4000}
// ]
```

> 💡Tip: it won't mutate the original array instead returns a new one

---

### pop()

syntax : `pop()`

removes the last element of the array and returns the element.

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let el = arr1.pop(); // output:laptop
// arr1=['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book']
```

> 💡Tip: it will mutate the original array

---

### shift()

syntax : `shift()`

removes the first element of the array and returns the element

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let el = arr1.shift(); // output:MONEY
// arr1=['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book']
```

> 💡Tip: it will mutate the original array

---

### push()

adds one or more elements to the array .returning the new length property value

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let el = arr1.push('flask', 'chair'); // output: 9
// arr1=['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book','flask','chair']
```

---

### reverse()

reversing an array and returning a reference to the mutated array.

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let el = arr1.reverse(); // output: ['laptop', 'book', 'laptop', 'mouse', 'laptop', 'monitor', 'MONEY']
//  el === arr1 -> true
```

> 💡Tip: it will mutate the original array

---

### some()

syntax : `some((item,index,array)=>/* ... */)`

`some` implement a test function on every element, if an element passes the test `some` returns true

```javascript
let arr1 = [
   { id: 1, product: 'mouse', quantity: 2, price: 40 },
   { id: 2, product: 'keyboard', quantity: 0, price: 150 },
   { id: 3, product: 'monitor', quantity: 4, price: 500 },
   { id: 1, product: 'watch', quantity: 4, price: 1000 },
];

let test = arr1.some(item => item.price > 500); // output: true
```

> 💡 Tip: returning any truthy value in the test function would amount to ture output

---

### sort()

syntax : `sort((firstEl,secondEl)=>/* ... */)`

accept a function as an argument (optional), comparing elements of an array and returning a reference to the sorted array.
different situation based on the return value of the function:

-  `1`: firstEl is bigger than secondEl
-  `-1`: firstEl is smaller than secondEl
-  `0`: firstEl is equal to secondEl
   by default, `sort` is a little bit tricky because it converts everything to string then sorts them out.

```javascript
let arr1 = [3, 10, 288, 2];
let sorted = arr1.sort(); // output: [10,2,288,3] !!!
```

the best practice is to implement our testing function

```javascript
let arr1 = [3, 10, 288, 2];
let ascending = arr1.sort((first, second) => first - second); // output: [2,3,10,288]
// or
let descending = arr1.sort((first, second) => second - first); // output: [288,10,3,2]
```

> 💡Tip: it will mutate the original array

---

### slice()

syntax : `slice(start,end)`

making a shallow copy and returning a new array. both `start` and `end` are optional and the default is `start:0`, `end:array.length` but when specified, `slice` makes a shallow copy (don't worry we'll talk about shallow copy) of the array from start to the end that we specified. there is a little hint, the end is not included
it's one of the most frequently used methods in libraries/frameworks just because of the fact it won't mutate the original array.

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let arr2=arr1.slice() // output:['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop']
let arr3=arr1.slice(1,4) :// output:['monitor', 'laptop', 'mouse']
```

> 💡Tip: it won't mutate the original array instead returns a new one

---

### splice()

syntax : `splice (( start , deleteCount , item1 , item2, ...))`

deleting or adding items to the original array. splice will change the length and items of the original array and returns the modified array as a reference to the original array.

-  the first argument is the index at which we want to start -> default : 0
-  the second argument is how many items we want to delete -> default: array. length - start
-  third argument and so are items that we want to add to the array. if there are no items it would just delete the items that we specified.

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let arr2=arr1.slpice(1,2) // output:['MONEY', 'mouse', 'laptop',book', 'laptop']

//or

let arr3=arr1.splice(1,2,'chair','honey') :// output:['MONEY','chair','honey', 'mouse', 'laptop',book', 'laptop']
// arr1 === arr3  ->  true

// or

let arr4=arr1.splice(1) // output: ['MONEY']
//arr1===arr4 -> true

```

> 💡Tip: it will mutate the original array

---

### ushift()

syntax : `unshift(item1,item2,....)`

adds items to the beginning of the original array and returning the length of the modified array

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let test = arr1.unshift('chair', 'desk'); // output:9
// arr1=['chair','desk','MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop']
```

> 💡Tip: it will mutate the original array.

---

### toString()

syntax: `toString()`

converts the items of the array to string and joins them by comma

```javascript
let arr1 = [4, 5, 'chair'];
let test = arr1.torString(); // output:'4,5,chair'
```

---

### flatMap()

syntax : `flatMap((item,index,array)=>/* ... */)`

it is a `map()` followed by the `flat()` method with a depth of 1.
it executes the function on each item of the array and then flats the array by one level then returns the flatted array.

```javascript
let arr1 = [1, 2, [3, 4], [5, [6, 7]]];
let arr2 = arr1.flatMap((item, index) => (item.isArray ? item * 2 : item[0] * 2)); // double the items if it's an array double the first item
// output : [ 2, 4, 6, 4, 10, [6, 7] ]
```

---

### reduce()

syntax : `reduce((acc,cur,index,array)=>/** ... */,initialValue)`

`reduce` execute a function on each item of an array then pass the return value to the next function as the first argument(`acc`).
the final result would be the last value returned by the function executed on the last item of the array(last `acc`)

-  with initialValue: sets `initalValue` as the `acc` on the first element
-  without initalValue: sets `acc` as the first item of the array and `cur` would be the second item. it starts from the second index

```javascript
let arr1 = [
   { id: 1, product: 'mouse', quantity: 2, countInStock: 0 },
   { id: 2, product: 'keyboard', quantity: 0, countInStock: 7 },
   { id: 3, product: 'monitor', quantity: 4, countInStock: 6 },
   { id: 1, product: 'watch', quantity: 4, countInStock: 0 },
];
let countAll = arr1.reduce((acc, cur) => acc.countInStock + cur.countInstock); // output:13
```

---

### reduceRight()

syntax : `reduceRight((acc,cur,index,arry)=>/* ... */)`

it's the same concept as `reduce` with a little bit of difference.`reduceRight` would start from right to left
functionality is the same but starting index is the last index of the array moving forward to the first index.

```javascript
let arr1 = [1, 2, -3, -4, 5];
let reducer = arr1.reduce((acc, cur) => (acc -= cur)); // output: 1
let reducerRight = arr1.rudeceRight((acc, cur) => (acc -= cur)); //output: 9
```

---

### Array.from()

syntax : `Array.from(array-like,mapFunction)`

it's an instance method that creates a shallow copy from an array-like
for example, when selecting a nodelist (span, div,...) the result is an array-like object that we can make a shallow copy by `Array.form()`
second argument (`mapFunction`) is optional`Array.from(array-like,mapFunction)` is the same as `Array.from(array-like).map(mapFunction)`

```javascript
let nodes = document.querySelectorAll('span');
let spanArray = Array.from(nodes); // now we can use any array method on the spanArray
```

---

### Array.isArray()

syntax : `Array.isArray(value)`

it's a useful method to check if the given argument is an array or not

```javascript
let test = Array.isArray(3); // false
let test2 = Array.isArray({ foo: 'bar' }); // false
let test3 = Array.isArray([1, 2, 3]); // true
```

---

### Array.of()

syntax : `Array.of(value1,value2,...)`

creates an array by given values

```javascript
let arr1 = Array.of(1, 2, 3); // [1,2,3]
let arr2 = Array.of([1, 2], { id: 1, product: 'mouse' }); //[[1,2],{id:1,product:'mouse"}]
```

---

there are other array methods :

-  [`enteries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries)
-  [`keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys)
-  [`groupBy()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/groupBy) (it is not supported by major browsers yet)

you can click the link to learn more about them but it's safe to say that it's used in special circumstances.

---

## combinations

now it's time to see them in action and how we can leverage array methods and combine them to come up with interesting ways for data manipulation

### filter, indexOf

question: an array consists of elements that are in both arr1 and arr2.

```javascript
let arr1 = ['MONEY', 'monitor', 'laptop', 'mouse', 'laptop', 'book', 'laptop'];
let arr2 = ['money', 'mouse', 'chair', 'desk', 'ice', 'case', 'monitor'];

let result = arr1.filter((item, index) => arr2.indexOf(item)); // [''mouse',monitor']
```

### every, slice

question : find out if the first five or the last five elements of an array are the same if any return `start` or `end` otherwise return false

```javascript
let arr1 = [
   'black',
   'black',
   'black',
   'black',
   'black',
   'black',
   'red',
   'red',
   'green',
   'black',
   'black',
];

function checkStartorEnd(arr) {
   let start = arr1.slice(0, 6).every(item => item === arr1[0]);
   let end = arr1
      .slice(arr.length - 5, arr.length)
      .every(item => item === arr1[arr.lenth - 1]);
   return start ? 'start' : end ? 'end' : false;
}
```


### reduce, map


 question: sum of goods in electronics

```javascript
let arr1 = [
   { id: 1, product: 'mouse', dept: 'electronics', countInStock: 3 },
   { id: 2, product: 'keyboard', dept: 'electronics', countInStock: 7 },
   { id: 3, product: 'monitor', dept: 'electronics', countInStock: 6 },
   { id: 4, product: 'watch', dept: 'electronics', countInStock: 9 },
   { id: 5, product: 'chair', dept: 'furniture', countInStock: 8 },
   { id: 6, product: 'desk', dept: 'furniture', countInStock: 15 },
   { id: 7, product: 'sofa', dept: 'furniture', countInStock: 4 },
];

let result = arr1
   .filter(item => item.dept === 'electronics')
   .reduce((acc, cur) => acc + cur.countInstock, 0);//25
```
------

**Now it's your turn,show us your ninja skills, how would you combine them ??**

_follow me on [Twitter](https://www.twitter.com/k1_kh89) I'd be happy to hear from you_