Array Cheatsheet
Tags: javascript, codenewbie
Published: 2020-05-13 18:57:26


A few days ago I came across a very nice post from Emma Bostian, a [RegExp Cheatsheet](https://dev.to/emmabostian/regex-cheat-sheet-2j2a).

And that post looked so useful at the time that it got me inspired to do something similar. So I picked arrays. Here is a small selection of methods which I believe if you keep them at hand, you’ll be a more productive JavaScript developer.

## Table of Contents

1. [flat](#flat)
2. [flatMap](#flatMap)
3. [every](#every)
4. [some](#some)
5. [reduceRight](#reduceRight)
1. [unshift](#unshift)
7. [slice](#slice)
6. [sort](#sort)
7. [from](#from)
8. [copyWithin](#copyWithin)
9. [lastIndexOf](#lastIndexOf)
10. [find](#find)
11. [findIndex](#findIndex)
12. [Breaking out of Loops](#breakout)


<h2 id="flat">flat</h2>

Reduce the number of layers in an array

```js
const bigArray = [[22], [33, 55, [23, 11], 50], 100, 109]

const oneLess = bigArray.flat()
// [22, 33, 55, [23, 11], 50, 100, 109]

const allGone = bigArray.flat(Infinity)
// [22, 33, 55, 23, 11, 50, 100, 109]
```

It accepts one param `depth: number`, which specifies the number of layers you to remove. Default is `1`.

> ⚡️ Check this video on `Array.flat()` in less than a minute!

{% youtube 74FqzrNalmY %}

<h2 id="flatMap">flatMap</h2>

Opposed to the name suggests, `flatMap()` is the same as `map().flat(1)`, not the other way around.

> 🚨 Notice the **1** to `flat()`.
  `flatMap` **always** runs with a `depth` of 1.

Because `flatMap` removes empty arrays, the output array does not need to have the same `length` as the original.

```jsx
const mutants = ['Wolverine', 'Storm', 'Jubilee', 'Cyclops']

// React-like environment. JSX 👇
const App = () => (
  <div>
    {mutants.flatMap((mutant, index) => [
      ...(index > 0 ? [', '] : []),
      <span>{mutant}</span>,
    ])}
  </div>
)

// Wolverine, Storm, Jubilee, Cyclops

```

> ⚡️ Check this video on `Array.flatMap()` in less than a minute!

{% youtube qSnblJ9HCCo %}

<h2 id="every">every</h2>

Receives a callback in the very same way as the more popular `map`, `filter`. Though `.every()` outputs a `boolean` stating if **every** item in the iterated `array` matches the condition in the callback.

```js
const menu = {
    type: '🍔',
    quantity: 'big',
  },
  {
    type: '🍕',
    quantity: 'big',
  },
  {
    type: '🍜',
    quantity: 'medium',
  },
]

const hasOnlyBigMeals = menu.every(({ quantity }) => quantity === 'big')

// false (🍜 is 'medium')

```

<h2 id="some">some</h2>

Receives a callback in the very same way as the more popular `map`, `filter` (and `every` right above). In the same way as `every`, it outputs a `boolean` describing the matched condition in the callback. Though, `some` returns `true` if at least **one** item in the `array` matches the condition.


```js
const menu = {
    type: '🍔',
    price: 10.9,
  },
  {
    type: '🍕',
    price: 3.9,
  },
  {
    type: '🍜',
    price: 8.9,
  },
]

const hasPricey = menu.some(({ price }) => price > 10)

// true (🍔 is above 10)
```
> ⚡️ Want to know more about checking your array for content? Watch this quick video about `some`, `every`, and `includes`!

{% youtube hIELd6NPNQQ %}

<h2 id="reduceRight">reduceRight</h2>

This one behaves exactly like the more popular `.reduce()` with the only exception that it runs in reverse other. Reduce-RIGHT. Get it? 😅

```js
const dogs = [
  'corgi',
  'beagle',
  'schnauzer'
]

dogs.reduceRight((acc, item, index, arr) => {
  return `${acc} ${item}${index === 0 ? ' 🦴' : ', '}`
}, '')

// schnauzer,  beagle,  corgi 🦴
```

<h2 id="unshift">unshift</h2>

Adds an element to the beginning of the `array`.

```js
const xmen = ['Cyclops', 'Jean Grey', 'Storm', 'Beast']
xmen.unshift('Wolverine')

// ['Wolverine', 'Cyclops', 'Jean Grey', 'Storm', 'Beast']

```

<h2 id="slice">slice</h2>

Returns a **shallow** copy of the passed `array` from `start` (defaults to first element) to `end` (defaults to last element).

```js
const xmen = [
  'Jubilee',
  'Kitty Pride',
  'Storm'
]

xmen.slice(0,2)
// ['Jubilee', 'Kitty Pride']

```

> ❗Pro-tip:
very useful for using mutating methods with Functional Programming paradigms

<h2 id="sort">sort</h2>

arranges the items in an array at a specific order. Default is ascending. It accepts a compare function as `callback`, first and second element are the respective params.

> 🚨 Careful! 
> elements will be coerced into `string`

```js
let numbers = [8, 1, 11, 4]

numbers.sort()
//['1', '11', '4', '8']

let numbersAgain = [8, 1, 11, 4]

numbersAgain.sort((a, b) => a - b)
// [1, 4, 8, 11]

numbersAgain.sort((a, b) => b - a)
// [11, 8, 4, 1]
```

If compare function returns
- less than 0: `a` goes before `b`
- 0: everything stays as is
- more than 0: `a` goes after `b`

<h2 id="from">from</h2>

creates a new, shallow-copied Array instance from an array-like or iterable.

```js
const object = {
  0: 'a'
  1: 'b'
  2: 'c'
  length: 3 // it needs to have length prop here
}

Array.from(object)

// ['a', 'b', 'c']
```

<h2 id="copyWithin">copyWithin</h2>

copies part of an `array` to the another location inside the **same** array without altering its length.

```js
const array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

array.copyWithin(1,4,7)
// ['a', 'e', 'f','g', 'e', 'f', 'g', 'h']

```

Copy to position `1` elements from index `4` to `7`.

<h2 id="lastIndexOf">lastIndexOf</h2>

returns the last possible index of an item in an `array`.

```js
const xmen = ['J.Madrox', 'Jubilee', 'J.Madrox', 'Wolverine', 'J.Madrox']

xmen.lastIndexOf('J.Madrox')
// 4

```

<h2 id="find">find</h2>

scans the `array` and returns the first element which satisfies the callback.

```js

const number = [55, 65, 39, 44]
const multiple3 = number.find(item => item % 3 === 0)
// 39

```

<h2 id="findIndex">find Index</h2>

scans the `array` and returns the `index` of the first element which satisfies the callback.

```js

const number = [55, 65, 39, 44]
const multiple3 = number.findIndex(item => item % 3 === 0)
// 2

```

<h2 id="breakout">Breakout of loops</h2>

it isn’t exactly trivial to stop a loop. In order to accomplish that, you need to mutate the array upon which the loop is happening, but you wouldn’t want to mutate when dealing with immutable data (like with the functional methods: map, reduce, filter, flat, flatMap, ...). 

Remember [slice](#slice)? Slice returns a subarray of the one it’s passed. We do that before we start, this means loop’s running on a shallow copy of the `array`.

To break out then, it’s just about using `.splice()`. Splice removes or 
replace elements in an `array`.

```js
const bigArray = new Array(100).fill(1)

const contentSum = bigArray
  .slice(0)
  .reduce((acc, item, index, array) => {
    if (index === 10) {
      array.splice(0)
    }

    console.log(index)
    return index
  }, 0)

// 10
```

---

What other methods would include in this list? Was there one or a few that you had never came across before? Let me know in the comments!!

Also, I hope you have found that useful. Please consider [sharing to your network](https://twitter.com/intent/tweet?text=Array Cheatsheet&via=AtilaFassina&url=https://dev.to/atila/array-cheatsheet) if you did, it would mean a lot to me! If you have any feedback to me regarding this or other posts of mine, feel free to reach out in the comments or on twitter!