6 Useful JavaScript Array Tricks That You Should Know
By: Mehdi Aoussiad
Tags: Javascript Tips, JavaScript, Web Development, Programming, Coding

6 Useful JavaScript Array Tricks That You Should Know

Photo by Mimi Thian on Unsplash

Introduction

An array is one of the common concepts of Javascript, it gives us a lot of possibilities to work with data stored inside of it. Arrays in general are one of the most basic topics in Javascript that you learn at the beginning of your programming path.

In this article, we will show you some useful and powerful array tricks that you may not know. Let’s get right into it.

Image created with ❤️️ By author.

1. Convert an array to an object

Sometimes, you will need to convert an array to an object in JavaScript. The best efficient way to do that is by using the spread operator {…} .

Have a look at the example below:

var fruits = ["banana", "apple", "orange"]; var fruitsObj = { ...fruits }; console.log(fruitsObj); // Returns : {0: "banana", 1: "apple", 2: "orange"}

As you can see, it’s much easier than it sounds if we use the spread operator.

2. Filling an array with data

There are some cases where you will need to fill an array with the same data type multiple times. You can achieve that by using the method fill .

Here is an example:

var newArray = new Array(5).fill("Hi"); console.log(newArray); // Returns: ["Hi", "Hi", "Hi", "Hi", "Hi"]

This method fill() can take any data type as an argument(strings, numbers…).

3. Get random values from an array

In many situations, the business logic of your program will need to get some random data from an array. The math methods Math.random() and Math.floor() help with that.

The method Math.random returns a random number between 0 and 1. On the other hand, the method Math.floor returns the largest integer less than or equal to a given number.

Notice that you have to write a capital letter M for the math methods.

Here is how we can get random array’s data using these methods:

const colors = ["red", "pink", "yellow", "black", "blue"]; const randomColor = colors[Math.floor(Math.random() * colors.length)]; console.log(randomColor); // Returns a random color from the "colors" array.

As you can see, the two methods above and the property length allow us to get a random number between 0 and the last index of the array colors (4). We put them in bracket notation which allows us to get random data from the array.

4. Remove duplicates from an array

Sometimes, you will need to remove duplicate values from an array. The most easier way to do that is by using the object set. That’s one of the popular JavaScript questions that are asked in coding interviews.

Have a look at the example below:

var fruits = ["banana", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple"]; // First method: var uniqueFruits = Array.from(new Set(fruits)); console.log(uniqueFruits); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”] // Second method: var uniqueFruits2 = [ ...new Set(fruits)]; console.log(uniqueFruits2); // returns [“banana”, “apple”, “orange”, “watermelon”, “grape”]

The object set makes it easier for us to remove duplicates from the array. It also keeps the code cleaner.

5. Find the intersection of two arrays

Let’s say you have two arrays and you want to get only the values that are included in both arrays.

You can use the object set to remove duplicates from the first array, then also use the method filter to filter from the first array(with unique values) only the values that are included in the second array.

Here is an example that achieves that:

var numOne = [0, 2, 4, 6, 8, 8]; var numTwo = [1, 2, 3, 4, 5, 6]; var duplicateValues = [...new Set(numOne)].filter(item => numTwo.includes(item)); console.log(duplicateValues); // Returns [2, 4, 6]

6. Use the length to resize and empty an array

In JavaScript, we can overwrite the length of an array. So, we will take this advantage to resize and empty an array.

Here is an example if we want to resize the array:

var entries = [1, 2, 3, 4, 5, 6, 7];

console.log(entries.length); // 7

entries.length = 4;

console.log(entries.length); // 4

console.log(entries); // [1, 2, 3, 4]

Here is another one if we want to empty the array:

var entries = [1, 2, 3, 4, 5, 6, 7];

console.log(entries.length); // 7

entries.length = 0;

console.log(entries.length); // 0

console.log(entries); // []

Conclusion

As you can see, we did many array tasks without having to write a lot of code. Using these array tricks will keep your code much cleaner and easy to maintain.

Thank you for reading this article, I hope you found it useful. If so, get more similar content by subscribing to our YouTube channel!

More Reading