JavaScript Transforming and Reordering Array Methods
Tags: javascript, node, tutorial, webdev
Published: 2021-03-02 19:45:14

### *map* method
The `map` method has its syntax shown below:

```
array.map(func)
```

`func` => `func` is the callback function.

See the example below:

```js
const fruits = [ "Apple", "Orange", "Melon", "Banana", "Advocado" ];

const fruitsFunc = item => {
  return item.length;
};

console.log( fruits.map(fruitsFunc) ); // [ 5, 6, 5, 6, 8 ]
```

---
### *sort* method
The `sort` method has its syntax shown below:

```
array.sort([func])
```

`func` is a callback function  

See the example below:

```js
const numbs = [ 1, 23, 2, 3, 12, 16, 31 ];

numbs.sort();

console.log(numbs); 

/*
[
   1, 12, 16, 2,
  23,  3, 31
]
*/
```

The method `sort()` reorders the content of `numbs` but not as we expect because the items are sorted as strings by default (lexicographic ordering).

This means the syntax `array.sort()` is best for string items.

See the example below:

```js
const fruits = [ "Apple", "Orange", "Melon", "Banana", "Advocado" ];

// the method reorders the content of arr
fruits.sort();

console.log(fruits);  // [ 'Advocado', 'Apple', 'Banana', 'Melon', 'Orange' ]
```

Let's use the callback function as a parameter in the sort function

```js
const compareNumeric = (a, b) => {
  if (a > b) return 1;
  if (a === b) return 0;
  if (a < b) return -1;
};

const numbs = [ 1, 23, 2, 3, 12, 16, 31 ];
numbs.sort(compareNumeric);

/*
[
   1,  2,  3, 12,
  16, 23, 31
]
*/
```

> The method is implements based on a generic sorting algorithm (mostly [quicksort](https://en.wikipedia.org/wiki/Quicksort) or [Timsort](https://en.wikipedia.org/wiki/Timsort)).

The example above is the same as shown below:

```js
const compareNumeric = (a, b) => {
  return a - b;
};

const numbs = [ 1, 23, 2, 3, 12, 16, 31 ];
numbs.sort(compareNumeric);
```

You can also reverse the ordering shown in the example above.

```js
const compareNumeric = (a, b) => {
  return b - a;
};

const numbs = [ 1, 23, 2, 3, 12, 16, 31 ];
numbs.sort(compareNumeric); 
/*
[
  31, 23, 16, 12,
   3,  2,  1
]
*/
```

> it's better to use the `str.localeCompare` method to correctly sort letters, such as `Ö`.

Below is another example:

```js
const countries = ['Österreich', 'Andorra', 'Vietnam'];

const func1 = (a, b) => { 
    return a > b ? 1 : -1 
};

console.log( countries.sort(func1) ); 
// Andorra, Vietnam, Österreich (wrong)

const func2 = (a, b) => {
    return a.localeCompare(b);
};

console.log( countries.sort(func2) ); 
// Andorra,Österreich,Vietnam (correct!)
```

---
### *reverse* method
The `reverse` method has its syntax shown below:

```
array.reverse([func])
```

`func` is a callback function  

See the examples below:

const numbs = [ 1, 2, 3, 4, 5 ];
numbs.reverse();

console.log(numbs); // [ 5, 4, 3, 2, 1 ]

```js
const numbs = [ 1, 23, 2, 3, 12, 16, 31 ];

numbs.reverse();

console.log( numbs ); 

/*
[
  31, 16, 12, 3,
   2, 23,  1
]
*/
```

In the example above, the `reverse` method only reverses the array stored in `numbs`. 

To properly reverse the array items we need to `sort` first before reversing.

See the example below:

```js
const compareNumeric = (a, b) => {
  return a - b;
};

const numbs = [ 1, 23, 2, 3, 12, 16, 31 ];

const sortOrder = numbs.sort(compareNumeric);
const reverseOrder = sortOrder.reverse();

console.log(reverseOrder);

/*
[
  31, 23, 16, 12,
   3,  2,  1
]
*/
```

---
### *split* and *join* methods
#### *split* method
The `split` method has its syntax shown below:

```
array.split(delit[, length])
```

`delim` => `delit` is the **delimiter** that splits the string into an array
`length` => The `length` is optional

See the example below:

```js
const names = 'Bello, Noah, Efosa, John, Osasu';

const messages = names.split(', ');

for (let name of messages) {
  console.log( `You have an unread message from ${name}.` ); 

/*
You have an unread message from Bello.
You have an unread message from Noah.
You have an unread message from Efosa.
You have an unread message from John.
You have an unread message from Osasu.
*/

};
```

The length property can also be used in the `split` function `split(delim, length)`. 

See the example below:

```js
const names = 'Bello, Noah, Efosa, John, Osasu';

const messages = names.split(', ', 3);

for (let name of messages) {
  console.log( `You have an unread message from ${name}.` ); 

/*
You have an unread message from Bello.
You have an unread message from Noah.
You have an unread message from Efosa.
*/

};
```

The `split` method can also convert a string to an array (object) of characters.

See the example below:

```js
const str = "Bello";

const toArray = str.split('')
console.log(toArray, typeof toArray); 
// [ 'B', 'e', 'l', 'l', 'o' ] object
```

#### *join* method
The `join` is the reverse of the `split` method. It creates a string of `array` items joined by `glue` between them.

See the syntax below:

```
array.join(glue)
```

See another example below:

```js
const str = [ 'Bello', 'Noah', 'Efosa', 'John', 'Osasu' ];

const toStr = str.join(';');
console.log( str.join(';') );
// Bello;Noah;Efosa;John;Osasu string
```

---
### *reduce* or *reduceRight* methods
The `reduce` method has its syntax shown below:

```
array.reduce(func)
```

> The `reduce` and `reduceRight` methods produce the same result but the `reduceRight` search is from right to left.

`func` => `func` is the callback function

See the example below:

```js
const numbs = [ 1, 2, 3, 4, 5 ];

const reducedFunc = (sum, current) => {
    return sum + current
};

const initial = 0;
const cummulateResult = numbs.reduce(reducedFunc, initial);

console.log(cummulateResult); // 15
// => 0 + (0 + 1 = 1), (0 + 1 + 2 = 3), (0 + 3 + 3 = 6), (0 + 6 + 4 = 10), (0 + 10 + 5 = 15)
// => initial + (initial + current1 = sum1), (initial + sum1 + current1 = sum2 ), ..., (initial + sumN + currentN = sumN+1 )
```

The table below is a representation of the example below:


|   calls        |      sum     |    current    |    result   |
|-------|-----------|------------|----------|
| first call  |    `0`     |     `1`    |   `1`       |
| second call  |     `1`      |     `2`     |      `3`      |
| third call  |      `3`         |      `3`      |      `6`     |
| forth call  |     `6`        |      `4`        |     `10`       |
| fifth call  |      `10`      |      `5`        |    `15`    |

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---