Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

13 Useful JavaScript Array Tips and Tricks You Should Know

Arrays are one of the most common concepts in Javascript, and they give us many possibilities for working with the data stored in them. Consider that arrays are one of the most basic topics in Javascript as you begin your programming journey. In this article, I’d like to give you some tips (which you may not know, but can be very useful in coding). Let’s get started.

1. Delete duplicates from the array

This is a popular interview question about Javascript arrays, how to extract unique values from Javascript arrays. Here’s a quick and simple solution that you can use with a new Set(). I want to show you two possible approaches, one using the.from() method and the other using the extension operator (…). .

varFruits = [" banana ", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple");// The first method
var uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits); / / return [" banana ", "apple", "orange", "watermelon", "grape"]

// The second method
varUniqueFruits2 = [...new Set(fruits)];
console.log(uniqueFruits2); / / return [" banana ", "apple", "orange", "watermelon", "grape"]
Copy the code

2. Replace specific values in the array

Sometimes when you create code you need to replace specific values in an array, and there is a nice short way to do this, but you may not know it yet. To do this, we can use the

.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Copy the code

And pass all three parameters specifying where we want to start modifying, the number of values we want to modify, and (multiple) new values.

varFruits = [" banana ", "apple", "orange", "watermelon", "orange", "grape", "apple"]; fruits.splice(0.2, “potato”, “tomato”);
console.log(fruits); / / return [" potato ", "tomato", "orange", "watermelon", "apple", "orange", "grape", "apple"]
Copy the code

3. Don’t.map()Mapping the array

Everyone probably knows about the.map() method for arrays, but different solutions can be used to get similar results and very clean code. To do this, we can use the.from() method.

var friends = [
    { name: ‘John’, age: 22 },
    { name: Peter,age: 23 },
    { name: ‘Mark’, age: 24 },
    { name: ‘Maria’, age: 22 },
    { name: Monica,age: 21 },
    { name: Martha,age: 19},]var friendsNames = Array.from(friends, ({name}) = > name);
console.log(friendsNames); / / return [" John ", "Peter", "Mark", "Maria", "Monica", "Martha"]
Copy the code

4. Empty the array

What if you have an array full of elements, but you need to clean it up for some purpose and don’t want to delete items one by one? You can do this with a single line of code. To empty the array, you need to set the length of the array to 0, and that’s it!

varFruits = [" banana ", "apple", "orange", "watermelon", "orange", "grape", "apple"]; fruits.length =0;
console.log(fruits); // returns []
Copy the code

5. Convert arrays to objects

It happens that we have an array, but for some purpose we need an object with that data, and the fastest way to convert an array to an object is to use the well-known extension operator (…). .

varFruits = [" banana ", "apple", "orange", "watermelon"];varFruitsObj = {... fruits };console.log(fruitsObj); / / returns {0: "banana", rank 1: "apple", 2: "orange", 3: "watermelon", 4: "apple", 5: "orange", 6: "grape", 7: "apple"}
Copy the code

6. Populate the array with data

In some cases, when we create an array, we want to populate it with some data, or we need an array with the same values, in which case the.fill() method provides a simple and clean solution.

var newArray = new Array(10). The fill ("1");console.log(newArray); / / return [" 1 ", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
Copy the code

7. Merge arrays

Do you know how to combine arrays into an array without using the.concat() method? There is a simple way to combine any number of arrays into one line of code. You may already be aware that when working with arrays, the extension operator (…) Very useful, in this case too.

varFruits = [" apple ", "banana", "orange"];varMeat = [" poultry ", "beef", "fish"];varVegetables = [" potato ", "tomato", "cucumber"];varFood = [... fruits,... meat,... vegetables];console.log(food); / / / "apple", "banana", "orange", "poultry", "beef", "fish", "potato", "tomato", "cucumber"]
Copy the code

8. Find the intersection of two arrays

This is also one of the most common challenges in Javascript interviews, because it tells you if you can use array methods and what your logic is. To find the intersection of two arrays, we will use one of the methods described earlier in this article to ensure that the values in the array we are examining are not duplicated, using the.filter and.include methods. Therefore, we get an array of values that are present in both arrays. Check code:

var numOne = [0.2.4.6.8.8];
var numTwo = [1.2.3.4.5.6];
varDuplicatedValues = [...new Set(numOne)].filter(item= > numTwo.includes(item));
console.log(duplicatedValues); // returns [2, 4, 6]
Copy the code

9. Delete false values from the array

First, let’s define false values. In Javascript, the false value is

false
0
""
null
NaN
undefined
Copy the code

Now let’s see how to remove these values from an array. To do this, we will use the.filter() method.

var mixedArr = [0And "blue", "",NaN.9.true.undefined"White",false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // Returns [" blue ", 9, true, "white"]
Copy the code

10. Get random values from arrays

Sometimes we need to randomly select a value from an array. To create it in a simple, quick, and short way, and keep the code clean, we can get a random index number based on the length of the array. Let’s look at the code:

varColors = "blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown"].var randomColor = colors[(Math.floor(Math.random() * (colors.length)))]
Copy the code

11. Reverse (flip) an array

When it comes to flipping an array, instead of having to go through complicated loops and functions to create it, there’s a simple array method that does everything for us, just one line of code, flipping an array. Let’s check:

varColors = "blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown"].var reversedColors = colors.reverse();
console.log(reversedColors); / / returns [" brown ", "black", "yellow", "orange", "purple", "pink", "navy" and "green", "white", "blue"]
Copy the code

12..lastIndexOf()methods

In Javascript, there is an interesting method that allows you to look up the index of the last occurrence of a given element. For example, if the array has duplicate values, we can find its last occurrence. Let’s look at a code example:

var nums = [1.5.2.6.3.5.2.3.6.5.2.7];
var lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // returns 9
Copy the code

13. Sum all the values in the array

Another challenge that often occurs in Javascript engineer interviews. There is nothing to be feared here; It can be solved in a single line of code using the.reduce method. Let’s look at the code:

var nums = [1.5.2.6];
var sum = nums.reduce((x, y) = > x + y);
console.log(sum); // returns 14
Copy the code

conclusion

In this article, I’ve presented you with 13 tips to help you write code and keep it short and clean. Also, keep in mind that there are many different tricks worth exploring in Javascript, not just with arrays, but with different data types. I hope you enjoy the solutions provided in this article and will use them to improve your development process.