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
- flat
- flatMap
- every
- some
- reduceRight
- unshift
- slice
- sort
- from
- copyWithin
- lastIndexOf
- find
- findIndex
- 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]
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 adepth
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
โก๏ธ 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')
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)
โก๏ธ Want to know more about checking your array for content? Watch this quick video about
some
,every
, andincludes
!
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 ๐ฆด
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']
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']
โ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 intostring
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 beforeb
- 0: everything stays as is
- more than 0:
a
goes afterb
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']
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']
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
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
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
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
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!
Top comments (3)
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 :)
Hahahaha... I'm glad you liked the post, Marcus!
Sorry about the code samples, I'll keep that in mind for the next ones! ๐
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.