14 Awesome JavaScript Array Tips You Should Know About

published

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); // "🍒"

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


You May Also Be Interested in the Following Posts