This post was originally published at kais.blog.
Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!
Update: Don't forget to check out 10 Awesome JavaScript String Tips You Might Not Know About!
Arrays are everywhere. Whenever you are working with JavaScript, you are probably using arrays. Often, programmers are using specific libraries to make arrays more usable. Yet, I'd like to show you 14 awesome tips about JavaScript arrays, you may not have known. This way, you can get rid of external dependencies. Use these simple code snippets instead.
- How to Use Array Destructuring
- How to Create a Duplicate-free Version of an Array
- How to Find All Elements Matching a Condition
- How to Remove All Falsy Values From an Array
- How to Find the First Element Matching a Condition
- How to Check If Any / Every Element Matches a Condition
- How to Find the Intersection of Two Arrays
- How to Find the Difference of Two Arrays
- How to Find the Union of Two Arrays
- How to Retrieve the First and Last Element
- How to Prepend / Append an Element to an Array
- How to Copy an Array
- How to Find the Minimum and Maximum Value From an Array
- How to Sort an Array of Numbers
1. How to Use Array Destructuring
With array destructuring you can extract single elements from a JavaScript array. Look at the following example:
const fruits = ["π", "π", "π"];
const apple = fruits[0];
console.log(apple); // "π"
const banana = fruits[1];
console.log(banana); // "π"
const cherry = fruits[2];
console.log(cherry); // "π"
We could rewrite the same using array destructuring:
const [apple, banana, cherry] = ["π", "π", "π"];
console.log(apple); // "π"
console.log(banana); // "π"
console.log(cherry); // "π"
Awesome! Also, you can skip certain elements, if you want to:
const [apple, , cherry] = ["π", "π", "π"];
console.log(apple); // "π"
console.log(cherry); // "π"
Note the empty slot above. You can skip any element you don't need, if you just leave out the variable name and add another comma.
Also, two other awesome things you can do with array destructuring:
// Assign a default value for a missing element.
const [apple, banana, cherry, melon = "π"] = ["π", "π", "π"];
console.log(melon); // "π"
// Get all remaining elements from an array using the rest operator (`...`).
const [apple, ...remainingFruits] = ["π", "π", "π"];
console.log(remainingFruits); // ["π", "π"]
There's even more you can do with array destructuring. Maybe I'll write another post about this later.
2. How to Create a Duplicate-free Version of an Array
To remove all duplicates from an array, people often use a library like lodash
. The library is by no means bad, however, there's a much easier way to do it. You can get all unique values with no external dependency. To do that, create a new Set
from your array. Then, use the spread operator (...
) to create a new array from your set. Because a set can only hold unique values, there are no duplicates left.
const fruits = ["π", "π", "π", "π", "π"];
// Create a new set from `fruits`, thereby removing all duplicates.
// Then, create a new array from it.
const uniqueFruits = [...new Set(fruits)];
console.log(uniqueFruits); // ["π", "π", "π"]
3. How to Find All Elements Matching a Condition
If you are working with arrays, sometimes you'd like to remove some elements. Maybe you want to remove odd numbers or you are just looking for short strings. Whatever you wish for, you can use Array#filter
for that.
const names = ["Kai", "Katharina", "Tim"];
// Keep names that are shorter than 4 characters.
const shortNames = names.filter(name => name.length < 4);
console.log(shortNames); // ["Kai", "Tim"]
// Find names that are longer than 10 characters.
const extraLongNames = names.filter(name => name.length > 10);
console.log(extraLongNames); // []
4. How to Remove All Falsy Values From an Array
Sometimes, your array contains falsy values, and you want to remove them. Falsy values are false
, null
, 0
, ""
, undefined
, and NaN
. You can filter them out very easily. For that, you can use the Array#filter
method again and simply check the element's truthiness:
const fruits = ["π", false, "π", undefined, "π"];
// Keep all array elements where `fruit` is truthy.
const filteredFruits = fruits.filter(fruit => fruit);
console.log(filteredFruits); // ["π", "π", "π"]
// This shows an alternative way to remove all falsy values from an array.
const filteredFruits = fruits.filter(Boolean);
5. How to Find the First Element Matching a Condition
Similar to 3., sometimes we just need the first element that matches our condition. So, we can make use of the Array#find
method.
const names = ["Kai", "Katharina", "Tim"];
// Find a name that is shorter than 4 characters.
const shortName = names.find(name => name.length < 4);
console.log(shortName); // "Kai"
// Find a name that is longer than 10 characters.
const extraLongName = names.find(name => name.length > 10);
console.log(extraLongName); // undefined
6. How to Check If Any / Every Element Matches a Condition
JavaScript arrays implement two awesome methods. Array#some
and Array#every
. Often, I'll notice that many people don't know these two. You can use them to check whether any element (Array#some
) or every element (Array#every
) matches a certain condition.
const names = ["Kai", "Katharina", "Tim"];
// Check if ANY name is shorter than 4 characters.
const containsShortName = names.some(name => name.length < 4);
console.log(containsShortName); // true
// Check if EVERY name is longer than 3 characters.
const containsLongNamesOnly = names.every(name => name.length > 3);
console.log(containsLongNamesOnly); // false
7. How to Find the Intersection of Two Arrays
When comparing two arrays, you might want to find out, which elements are included in both arrays. That means, we want to find the intersection of both arrays. So, we can use a combination of Array#filter
and Array#includes
.
const fruitsA = ["π", "π", "π"];
const fruitsB = ["π", "π", "π", "π"];
const intersection = fruitsA.filter(fruit => fruitsB.includes(fruit));
console.log(intersection); // ["π", "π"]
8. How to Find the Difference of Two Arrays
Similar to 7. we can use combine Array#filter
and Array#includes
to find the difference between two arrays. The implementation differs on whether you want to include relevant elements from the second array or not.
const fruitsA = ["π", "π", "π"];
const fruitsB = ["π", "π", "π", "π"];
// Keep all elements from `fruitsA` that are not included in `fruitsB`.
const difference = fruitsA.filter(fruit => !fruitsB.includes(fruit));
console.log(difference); // ["π"]
// Keep all elements from `fruitsA` that are not included in `fruitsB` and vice versa.
const difference = [
...fruitsA.filter(fruit => !fruitsB.includes(fruit)),
...fruitsB.filter(fruit => !fruitsA.includes(fruit)),
];
console.log(difference); // ["π", "π", "π"]
9. How to Find the Union of Two Arrays
Maybe you want to merge two arrays and throw out all duplicates. Good thing you've learned how to remove duplicates in tip 2. We'll use the spread operator (...
) and a set again.
const fruitsA = ["π", "π", "π"];
const fruitsB = ["π", "π", "π", "π"];
// Merge `fruitsA` and `fruitsB`. Then, use a set for removing duplicates.
// After that, create a new array from the set.
const union = [...new Set([...fruitsA, ...fruitsB])];
console.log(union); // ["π", "π", "π", "π", "π"]
10. How to Retrieve the First and Last Element
From time to time, the only element you are interested in is the first or last one. A straightforward way to access them are the Array#shift
and Array#pop
methods. However, note, that these will remove the first and last element from the array. Sometimes, you don't want to change your original array.
const fruits = ["π", "π", "π"];
// Find the first element. Attention! This modifies the original array.
const first = fruits.shift();
console.log(first); // "π"
// Find the last element. Attention! This modifies the original array.
const last = fruits.pop();
console.log(last); // "π"
// Remember, both methods modify the original array.
console.log(fruits); // ["π"]
11. How to Prepend / Append an Element to an Array
You'll probably know this. But, just in case, I'm telling you how you can prepend or append an element to a JavaScript array. While almost everyone knows how to add an element to the end of an array. Sometimes, people don't know how to add an element to the beginning. I'll show you both ways. Also, I'll show you how to add multiple elements at once.
const fruits = ["π", "π", "π"];
// Append an element with `Array#push`.
// This means, we'll add it to the end.
fruits.push("π");
console.log(fruits); // ["π", "π", "π", "π"];
// Prepend an element with `Array#unshift`.
// This means, we'll add it to the beginning.
fruits.unshift("π");
console.log(fruits); // ["π", "π", "π", "π", "π"];
// You can also add multiple items at once.
// Works with `push` and `unshift`.
fruits.push("π", "π");
fruits.unshift("π", "π");
// Also, you could use the spread operator (...).
// This would add all elements from another array.
fruits.push(...["π", "π"]);
fruits.unshift(...["π", "π"]);
12. How to Copy an Array
As you have seen in the tips before, some actions change your original array. Sometimes this is undesirable. Thus, we somehow need to copy it. A simple way to do this is using the Array#slice
method.
// This example is similar to tip 11.
const fruitsA = ["π", "π", "π"];
// Here, we copy the `fruitsA` array.
const fruitsB = fruitsA.slice();
// Find the first element. Attention! This modifies our `fruitsB` array.
const first = fruitsB.shift();
console.log(first); // "π"
// Find the last element. Attention! This modifies our `fruitsB` array.
const last = fruitsB.pop();
console.log(last); // "π"
// This time, our original arrays stays intact.
// Only `fruitsB` has changed.
console.log(fruitsA); // ["π", "π", "π"]
console.log(fruitsB); // ["π"]
// This shows an alternative way to copy an array.
const fruitsB = [...fruitsA];
CAUTION! This does not create a deep copy. Objects and nested arrays are passed by reference. So, let's say fruitsA
would contain an object, and you'd copy the array into fruitsB
. Then, you'd take out this object from fruitsB
and modify it. You might think this would leave your initial array intact. But, sorry to say that, you are wrong. The object you retrieved from fruitsB
still referenced the object from fruitsA
. Thus, any change to the object in fruitsB
would be mirrored to the same object in fruitsA
. This is important to remember! For deep copies, consider using a dedicated library.
13. How to Find the Minimum and Maximum Value From an Array
If you are working with a lot of numbers, there'll be the time you must find the minimum or maximum value. Probably, you know that you can use Math#min
and Math#max
. Combine that with the spread operator (...
) and you can easily check the full array for its minimum and maximum value.
const priceHistory = [450, 500, 330, 600, 910];
// Find the minimum value.
const minimumPrice = Math.min(...priceHistory);
console.log(minimumPrice); // 330
// Find the maximum value.
const maximumPrice = Math.max(...priceHistory);
console.log(maximumPrice); // 910
14. How to Sort an Array of Numbers
If you want to sort an array, you'll probably use Array#sort
. But, numbers aren't sorted the way you'd think. When sorting arrays in JavaScript, it converts the elements to strings by default. Then, the elements are sorted by comparing their UTF-16 codepoints. For numbers, this could cause an unexpected order. So, we'll change the default behaviour and pass a function to the Array#sort
method. It works by always comparing two elements (a
and b
) at a time. If the result is less than 0, a
comes first. If the result is greater than 0, b
comes first.
const numbers = [15, 52, 23, 11, 9];
// Sort in ascending order. Attention! This modifies the original array.
numbers.sort((a, b) => a - b);
console.log(numbers); // [9, 11, 15, 23, 52]
// Sort in descending order. Attention! Again, this modifies the original array.
numbers.sort((a, b) => b - a);
console.log(numbers); // [52, 23, 15, 11, 9]
Conclusion
You can use arrays for a wide range of things. Often, there are simple native ways that do the job. Maybe you already knew these tips. Maybe not. Nevertheless, I hope this post was interesting for you. I'll try to update this post with new tips in the future.
Thanks a lot for reading this post. Please consider sharing it with your friends and colleagues. See you soon!
Update: Don't forget to check out 10 Awesome JavaScript String Tips You Might Not Know About!
Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!
This post was originally published at kais.blog.
Top comments (12)
An easier way to copy an array:
I was also looking if this method is mentioned in the article.
Thank you for the nice tips!
You can also use simple coercion to
Boolean
Was about to suggest this as well. Much cleaner to me :-)
Please don't use emojis.
When your browser doesn't render emojis you get Replacement Glyph.
Thanks for your feedback! What browser are you using?
Latest Chrome on Win7 with almost all fonts deleted.
You should probably write that copying array/object with spread operator/slice/object.assign/json technique is just shallow copying - which is important information. Also you can use
Object.assign([], [your array])
and another oneJSON.parse(JSON.stringify([your array]))
(but I would not recommend it to you) :)You can also do
[1, 2, 3, 4, null, 5, undefined].filter(Boolean)
to remove falsey values.Nice one! Thanks
awesome tips
Absolutely amazing. I've started learning react and I noticed that I'll be dealing with arrays of different sorts. This article is quite helpful.