Exploring All Javascript Array Methods
Tags: javascript
Published: 2023-11-25 11:36:28

In this article I will discuss various methods that I often encounter which are used to process data with array data types, please read, study and practice so you don't forget.

So let's get started.

## Map

At this article i will talk about one method in javascript that very often used in commonly, that's is `map()` so let's go..

This method by the way including methods that have been around for a long time in JavaScript, they were added during the ES5 version of JavaScript around 2009.

We can use this method to populate new array based on custom condition in your array.

Example i have array like this.

```js
let a = [2,3,4,2,1,7,8,11]
let b = a.map(v => {
  return v * 10
})

// [20, 30, 40, 20, 10, 70, 80, 110]
```

At above I created a new array where it is created with each element of the variable a multiplied by 10.

Or we can add and delete field inside element of object.

```js
let a = [
  {
  count: 10,
  name: 'Muhammad ichsan'
  },
  {
  count: 119,
  name: 'Ichsan'
  }
]

// delete field object element
let b = a.map(v => {
  return {
    count: v.count
  }
})

// add field object element
let c = a.map(v => {
  return {
    ...v,
    date: 'now'
  }
})
```
Here you can also do conditioning on the return value, in the example below, it will return all fields on the object if the count value on the element is not 119, if it is 119 then it will only return the count field.

```js
let b = a.map(v => {
  if (v.count == 119){
    return {
      count: v.count
    }
  }

   return {
      ...v
   }
})
```
Array map have 3 argumen on callback, there are is `(element, index_of_element, its array)`.

## Concat

`array.concat()` is used for combining two array, this method not manipulate first and second array but this will be returning new array with element's from first array plus second array.

```js
let arr1 = [1,2,3]
let arr2 = [4,5,6]

let arr3 = arr1.concat(arr2)
// [1,2,3,4,5,6]
```

## CopyWithin

`copyWithin()` method will be copy range of element into particular index of array. Example i want move 'd','e', and 'f' into start from first index array.

```js
const array1 = ['a', 'b', 'c', 'd', 'e', 'f'];
console.log(array1.copyWithin(0, 3, 6));
// ['d', 'e', 'f', 'd', 'e', 'f']
```

Format this method like this `array.copyWithin(targetindex, startindexelement, endindexelement)`. Noted for endindexelement, if you choose example startindex is 3 and endindexelement 6 they will be copy element from index 3 until 5 not 6.

## Every

`every()` method basically will be return true if looping elemen condition also return true all, if there is one loop element that returns a false value then the result of every method will still be false.

Example at here i want check whether all e elements in my array value exceed 100 or not.

```js
const array1 = [111, 310, 119, 129, 110, 113];
console.log(array1.every(v => v > 100));
// true
```

If there is just one loop that does not produce true, then every method will produce false.

```js
const array1 = [111, 310, 119, [9,4], 110, 113];
console.log(array1.every(v => v > 100));
// false
```

Just like other array loops, in the callback you will also get 3 arguments, namely `(value, index, array)`.

## Filter

Next is `filter()`, this method actually have same mechanisme with `map()`. Both of them will be returning new array based on conditional in looping.

But of course there are differences between the two, as we know that the resulting map array will have the same number of elements as the initial array. This is different from filters, where we can delete elements that do not match the conditions we set.

The behavior of elements that do not match the conditions is that the map will fill the element with undefined or change its value while the filter will completely disappear.

```js
const array = [111, 310, 119, 99, 110, 113];

const array1 = array.filter(v => v > 100);
const array2 = array.map(v => {
  if (v > 100){
    return v
  }
});
console.log(array1)
// [111, 310, 119, 110, 113]
console.log(array2)
// [111, 310, 119, undefined, 110, 113]
```

## Flat

The `flat()` method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

`flat` method accept one parameter thats is for define depth array that we want to be flatted.

```js
let arr = [1, 2, [3, 4, [5, 6]]];
console.log(arr.flat())
// [1, 2, 3, 4, [5,6]]
```

This method by the way not suporting to object element, if you want flat an array inside object element maybe you can iterate first the element using `map` or `forEach`.

## FlatMap

Actually this method is a combination of map and flat with a depth of 1, what this method does is do the map first then if there is a 1 level nested array then it will run flat.

`flatMap()` will be running like this.

```js
const arr = [1, 2, 1,] ;

const result = arr.map(v => [v, 100]).flat();
const result = arr.flatMap(v => [v, 100]);

```

## ForEach

A method that must be familiar to your ears, the `forEach()` method is used to loop elements in an array with the same parameters, namely element, index and array.

In contrast to the map in foreach, we cannot manipulate the elements with returns, to change the value of the element we can use an array of arguments and indexes.

This below code i change value to 199 at element with have value 5.

```js
let y = [5,4,4,4,4,4]

y.forEach((v, i, arr) => {
  console.log(v)
  console.log(i)
  console.log(arr)

  if (v == 5){
    arr[i] = 199
  }
})
```
So what's the difference with a map?

The difference is that in map we have to use return to manipulate elements or return elements, while in foreach we don't need return at all in the code block.

## Reduce 

This method is actually the same as foreach and map, the difference is that there is one more parameter given to the callback, namely the _accumulator_.

_accumulator_ is value that be returned from previous looping, for first looping value of _accumulator_ is first index of array. And for first value for _current value_ in first looping is element at index 1.

The structure for this method especially in parameter like this.

```js
let y = [5,6,4]

y.reduce((pv, cv, ci, arr) => {
  console.log(pv)
  console.log(cv)
  console.log(ci)
  console.log(arr)

  return 9
})
```

- pv = accumulator
- cv = current value
- ci = current index
- arr = its array

Its only shortname that i given alone, you can give custom name of parameter with freely.

## Slice

Slice will receive 2 parameters, the first is the start index and the second is the end index of the array. This method will return an array with the results of deleting elements based on the start and end index that we set.

If we not pass end index then the slice method will cut elements at index less than the start index. In the example below, I enter 3 as the start index, and what happens is that the slice will cut elements at index 2, 1, and 0.

```js
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(3));
// ['duck', 'elephant']
```
We can also enter a negative value in the start index. What happens is that elements in the array will be left for the right side, for example I enter -2 below, then the result is that I get the first 2 elements from the last.

```js
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(-2));
// ['duck', 'elephant']
```

For example, here I will take the camel and duck values using the end index. Both are located at index 2 and 3, therefore I set the start index to 2 which will take the element at index 2 and set the end index to 4 because the limit is less than 4.

```
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2,4));
```

## Splice

Different from slice, this splice method is more precisely used to replace elements in a certain index range. The syntax like this.

```js
splice(start, deleteCount, item1, item2, /* …, */ itemN)
```

Example I want to replace the elements at the first index with the 3 values that I define below.

```js
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 2, 'May', 'December', 'November');
// ["Jan", "May", "December", "November", "June"]
```

We can also use this to delete elements at a certain index by not entering the value that will be included in replace in the third argument.

## Some

The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

This is the opposite of the every method which requires all looping elements to produce true values.

```js
const array = [1, 2, 3, 121, 5];
const even = (v) => v > 100;

console.log(array.some(even));
// true
```

## Shift & Pop

Shift and Pop are both used to delete one element in an array. Shift is used to delete the first element, while pop is used to delete the last element.

These two methods do not produce a new array but instead manipulate the array used.

```js
const array = [1, 2, 3];
array.shift();
// [2,3]
array.pop();
// [2]
```