DEV Community

loading...
Cover image for Array Cheatsheet

Array Cheatsheet

atila profile image Atila Fassina Originally published at atila.io Updated on ・5 min read

A few days ago I came across a very nice post from Emma Bostian, a RegExp Cheatsheet.

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
  2. flatMap
  3. every
  4. some
  5. reduceRight
  6. unshift
  7. slice
  8. sort
  9. from
  10. copyWithin
  11. lastIndexOf
  12. find
  13. findIndex
  14. Breaking out of Loops

flat

Reduce the number of layers in an array

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]
Enter fullscreen mode Exit fullscreen mode

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!

flatMap

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.

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

Enter fullscreen mode Exit fullscreen mode

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

every

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.

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

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

// false (🍜 is 'medium')

Enter fullscreen mode Exit fullscreen mode

some

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.

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)
Enter fullscreen mode Exit fullscreen mode

⚡️ Want to know more about checking your array for content? Watch this quick video about some, every, and includes!

reduceRight

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

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

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

// schnauzer,  beagle,  corgi 🦴
Enter fullscreen mode Exit fullscreen mode

unshift

Adds an element to the beginning of the array.

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

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

Enter fullscreen mode Exit fullscreen mode

slice

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

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

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

Enter fullscreen mode Exit fullscreen mode

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

sort

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

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]
Enter fullscreen mode Exit fullscreen mode

If compare function returns

  • less than 0: a goes before b
  • 0: everything stays as is
  • more than 0: a goes after b

from

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

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

Array.from(object)

// ['a', 'b', 'c']
Enter fullscreen mode Exit fullscreen mode

copyWithin

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

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

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

Enter fullscreen mode Exit fullscreen mode

Copy to position 1 elements from index 4 to 7.

lastIndexOf

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

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

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

Enter fullscreen mode Exit fullscreen mode

find

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


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

Enter fullscreen mode Exit fullscreen mode

find Index

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


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

Enter fullscreen mode Exit fullscreen mode

Breakout of loops

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 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.

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
Enter fullscreen mode Exit fullscreen mode

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 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!

Discussion (3)

pic
Editor guide
Collapse
marcusatlocalhost profile image
Marcus

Learned a lot here. I also learned how hard it is to read code samples with emojis in them. Maybe I'm too old for that :)

Collapse
atila profile image
Atila Fassina Author

Hahahaha... I'm glad you liked the post, Marcus!
Sorry about the code samples, I'll keep that in mind for the next ones! 😅

Collapse
marcusatlocalhost profile image
Marcus

Oh well, I can see, that emojis help to keep the samples short and often tell a story to make it easier to understand code.