DEV Community

Cover image for 14 Awesome JavaScript Array Tips You Should Know About
Kai
Kai

Posted on • Edited on • Originally published at kais.blog

14 Awesome JavaScript Array Tips You Should Know About

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.

  1. How to Use Array Destructuring
  2. How to Create a Duplicate-free Version of an Array
  3. How to Find All Elements Matching a Condition
  4. How to Remove All Falsy Values From an Array
  5. How to Find the First Element Matching a Condition
  6. How to Check If Any / Every Element Matches a Condition
  7. How to Find the Intersection of Two Arrays
  8. How to Find the Difference of Two Arrays
  9. How to Find the Union of Two Arrays
  10. How to Retrieve the First and Last Element
  11. How to Prepend / Append an Element to an Array
  12. How to Copy an Array
  13. How to Find the Minimum and Maximum Value From an Array
  14. 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); // "πŸ’"
Enter fullscreen mode Exit fullscreen mode

We could rewrite the same using array destructuring:

const [apple, banana, cherry] = ["🍎", "🍌", "πŸ’"];

console.log(apple); // "🍎"
console.log(banana); // "🍌"
console.log(cherry); // "πŸ’"
Enter fullscreen mode Exit fullscreen mode

Awesome! Also, you can skip certain elements, if you want to:

const [apple, , cherry] = ["🍎", "🍌", "πŸ’"];

console.log(apple); // "🍎"
console.log(cherry); // "πŸ’"
Enter fullscreen mode Exit fullscreen mode

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); // ["🍌", "πŸ’"]
Enter fullscreen mode Exit fullscreen mode

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); // ["🍎", "🍌", "πŸ’"]
Enter fullscreen mode Exit fullscreen mode

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); // []
Enter fullscreen mode Exit fullscreen mode

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); // ["🍎", "🍌", "πŸ’"]
Enter fullscreen mode Exit fullscreen mode
// This shows an alternative way to remove all falsy values from an array.
const filteredFruits = fruits.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

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

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

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); // ["🍌", "πŸ’"]
Enter fullscreen mode Exit fullscreen mode

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); // ["🍎", "πŸ†", "πŸ‰"]
Enter fullscreen mode Exit fullscreen mode

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); // ["🍎", "🍌", "πŸ’", "πŸ†", "πŸ‰"]
Enter fullscreen mode Exit fullscreen mode

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); // ["🍌"]
Enter fullscreen mode Exit fullscreen mode

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(...["🍍", "🍊"]);
Enter fullscreen mode Exit fullscreen mode

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); // ["🍌"]
Enter fullscreen mode Exit fullscreen mode
// This shows an alternative way to copy an array.
const fruitsB = [...fruitsA];
Enter fullscreen mode Exit fullscreen mode

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

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

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)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

An easier way to copy an array:

const fruitsA = ["🍎", "🍌", "πŸ’"];
const fruitsB = [...fruitsA];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
picwellwisher12pk profile image
Amir Hameed

I was also looking if this method is mentioned in the article.

Collapse
 
olvnikon profile image
Vladimir

Thank you for the nice tips!

How to Remove All Falsy Values From an Array

You can also use simple coercion to Boolean

const fruits = ["🍎", false, "🍌", undefined, "πŸ’"];

const filteredFruits = fruits.filter(Boolean);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hilleer profile image
Daniel Hillmann

Was about to suggest this as well. Much cleaner to me :-)

Collapse
 
kamcio profile image
kamcio • Edited

A screenshot of JavaScript code with Replacement Glyphs in place of some emojisPlease don't use emojis.
When your browser doesn't render emojis you get Replacement Glyph.

Collapse
 
kais_blog profile image
Kai

Thanks for your feedback! What browser are you using?

Collapse
 
kamcio profile image
kamcio

Latest Chrome on Win7 with almost all fonts deleted.

Collapse
 
szymondziewonski profile image
Szymon DziewoΕ„ski • Edited

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 one JSON.parse(JSON.stringify([your array])) (but I would not recommend it to you) :)

Collapse
 
thelogicwarlock profile image
Kaemon Lovendahl

You can also do [1, 2, 3, 4, null, 5, undefined].filter(Boolean) to remove falsey values.

Collapse
 
ebrima2ray1 profile image
Ebrima Touray

Nice one! Thanks

Collapse
 
codejackdev profile image
Code Jack

awesome tips

Collapse
 
panshak profile image
Panshak

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.