Photo by Elisa Calvet B.
Intro
There are so many ways to create and manipulate arrays in JavaScript that it can be confusing at first. And even after years of practice, it can still be hard to remember which method to use, and when. This post aims to provide something like a "cheat sheet" with the most common array methods by use case, with concise examples. I truly believe that learning from examples is one of the best ways of learning, as long as you practice independently. Feel free to bookmark this post and come back anytime you need ๐
1. Populating
6 ways to create and populate this array: [ 'fruit', 'fruit', 'fruit', 'fruit', 'fruit' ]
const fruits = ['fruit', 'fruit', 'fruit', 'fruit', 'fruit']
const fruits = new Array(5)
for (let i=0; i<test.length; i++) {
fruits[i] = 'fruit'
}
const fruits = new Array(5).fill('fruit')
const fruits = Array.from({length: 5}, () => 'fruit')
const fruits = [...new Array(5)].map(() => 'fruit')
const fruits = ['fruit', 'fruit', 'fruit'].concat(['fruit', 'fruit'])
Let's consider this array of objects:
const fruits = [
{ name: "apple", quantity: 3 },
{ name: "orange", quantity: 5 },
{ name: "pear", quantity: 1 },
{ name: "banana", quantity: 0 },
]
We can build a new array without mutating the original array in various ways, depending on the needs:
fruits.map(fruit => fruit.name)
fruits.map((fruit, idx) => {
let str = `#${idx + 1} ${fruit.name} (${fruit.quantity})`
return str
})
fruits.filter(fruit => fruit.quantity === 0)
fruits.reduce((total, fruit) => total + fruit.quantity, 0)
fruits.slice(0, 2)
console.log(fruits)
Or we can directly modify the original array:
fruits.pop()
console.log(fruits)
fruits.push({name: 'kiwi', quantity: 2}, {name: 'strawberry', quantity: 14})
console.log(fruits)
fruits.shift()
console.log(fruits)
fruits.unshift({ name: 'cherry', quantity: 7 })
console.log(fruits)
The Array.splice method can also be used to change an array by removing and adding elements. It returns the removed elements (or an empty array if no elements were removed).
let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(0, 2)
console.log(colors)
let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(1)
console.log(colors)
let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(2, 2, 'pink', 'orange')
console.log(colors)
let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(2, 0, 'red', 'white')
console.log(colors)
3. Making assertions
const fruits = [
{ name: "apple", quantity: 3 },
{ name: "orange", quantity: 5 },
{ name: "pear", quantity: 1 },
{ name: "banana", quantity: 0 },
]
fruits.some(fruit => fruit.quantity === 0)
fruits.every(fruit => fruit.quantity === 0)
const shoppingList = ['bread', 'milk', 'cofee', 'sugar']
shoppingList.includes('bread')
shoppingList.includes('orange')
4. Ordering
const numbers = [4, 1, 8, 3, 5]
numbers.sort((a, b) => b - a)
numbers.sort((a, b) => a - b)
const numbers = [4, 1, 8, 3, 5]
const sortedNumbers = [...numbers].sort((a, b) => a - b)
5. Searching
const fruits = ['apple', 'orange', 'banana', 'apple', 'kiwi']
fruits.indexOf('apple')
fruits.indexOf('kiwi')
fruits.indexOf('pear')
fruits.lastIndexOf('apple')
const numbers = [1, 32, 12, 8, 4, 17]
numbers.find(number => number > 10)
6. Arrays & Strings
const words = ['Hello', 'wonderful', 'world']
words.join(' ')
const sentence = "Hello wonderful world"
sentence.split(' ')
๐ Bonus: tips & tricks
Chaining
Many of the methods mentionned above return an array, which allow us to chain them like so:
const fruits = [
{ name: "apple", quantity: 3 },
{ name: "orange", quantity: 5 },
{ name: "pear", quantity: 1 },
{ name: "banana", quantity: 0 },
]
fruits
.sort((fruit1, fruit2) => fruit2.quantity - fruit1.quantity)
.filter(fruit => fruit.quantity > 0)
.map(fruit => `${fruit.name} (${fruit.quantity})`)
.join(', ')
Spreading
There are various use cases when spreading an array is really useful:
const arrayCopy = [...originalArray]
const arrayWithNewElements = [newItem, ...originArray, anotherItem]
const mergedArrays = [...array1, ...array2, ...array3]
const arrayFromSet = [...new Set(elements)]
const populatedArray = [...new Array(10)].map((_, idx) => idx)
const fruits = ['apple', 'orange', 'banana', 'kiwi']
console.log({...fruits})
Remove duplicates
3 ways to remove duplicates from an array:
const array = ['๐',1,2,'๐','๐',3,4];
const distinct_array = [...new Set(array)];
const distinct_array = array.filter((item, idx) => array.indexOf(item) === idx);
const distinct_array = array.reduce((unique, item) =>
unique.includes(item) ? unique : [...unique, item]
)
Empty an array
const fruits = ['apple', 'orange', 'banana', 'kiwi']
fruits.length = 0
console.log(fruits)
Remove falsy values
const values = [false, 12, 'test', null, true]
values.filter(Boolean)
That's all for today's breakfast folks. If you liked this post, feel free to share it with your friends/colleagues and leave your thoughts in the comments!
Have a fantastic day,
With ๐งก, Yohann