Three articles are expected to be translated as follows:

  • 9 Projects that will Make you a Front End Expert by 2020
  • Preloading responsive images is implemented in Chrome 73
  • 13 Useful JavaScript Array Tricks you should know

Why am I creating this Git repository? Learn and follow up new ideas and technologies of web development by translating foreign Web related technical articles. Git repository address: github.com/yzsunlei/ja…

Arrays are one of the most common concepts in Javascript, and they give us many possibilities for working with the data stored in them. Given that arrays are one of the most fundamental topics in the Javascript language that you can learn about at the beginning of your programming, in this article I want to show you some tricks that you might not know about and could be very useful. To help you code! Let’s get started.

1. Remove duplicates from the array

This is a very popular interview question about Javascript arrays, how to extract unique values from Javascript arrays. This is a quick and easy solution to this problem, for which you can use the new Set(). I want to show you two possible methods, one using the.from() method and the second using the expansion operator (…). .

var fruits = ["banana"."apple"."orange"."watermelon"."apple"."orange"."grape"."apple"];

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

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

Simple, right?

2. Replace specific values in the array

Sometimes it’s necessary to replace a particular value in an array when creating code, and there’s a nice neat way to do it that you might not know about. To do this, we can use.splice(start, valueToRemove, valueToAdd) and pass in all three parameters, which specify where to start the modification, how many values to change, and add new values.

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

3. There is no map array of.map()

Everyone probably knows about the.map() method for arrays, but you can use another solution to achieve a similar effect and the code is very concise. 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);
// returns ["John", "Peter", "Mark", "Maria", "Monica", "Martha"]
Copy the code

4. Empty the array

Do you have an array full of elements, but need to clean it up for some purpose and don’t want to delete items one by one? Just one line of code. To empty the array, you need to set the length of the array to 0, and that’s it!

var fruits = ["banana"."apple"."orange"."watermelon"."apple"."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 this data, and the fastest way to convert an array to an object is to use the well-known expansion operator (…). .

var fruits = ["banana"."apple"."orange"."watermelon"];
varfruitsObj = { ... fruits };console.log(fruitsObj);
// returns {0: "banana", 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 convenient solution.

var newArray = new Array(10).fill("1");
console.log(newArray);
// returns ["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. As you may be aware, when working with arrays, the expansion operator (…) Very useful, even in this case.

var fruits = ["apple"."banana"."orange"];
var meat = ["poultry"."beef"."fish"];
var vegetables = ["potato"."tomato"."cucumber"];
var food = [...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 you’re likely to face in any Javascript interview, as it indicates whether you can use array methods and what your logic is. To find the intersection of two arrays, we will use one of the methods shown earlier in this article to ensure that the values in the array we are checking are not duplicated, and we will use the.filter and.includes methods. As a result, we get an array of values that exist in both arrays. Check code:

var numOne = [0.2.4.6.8.8];
var numTwo = [1.2.3.4.5.6];
var duplicatedValues = [...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, false values are false, 0, “, null, NaN, undefined. Now we can find out how to remove such values from the array. To do this, we will use the.filter() method.

var mixedArr = [0."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 our code clean, we can get random indexes based on the array length. Let’s look at the code:

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

11. Reverse the array

When we need to reverse arrays, instead of creating them through complicated loops and functions, there is a simple array method that does all the work for us, and with a single line of code, we can reverse arrays. Let’s check:

var colors = ["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", "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 our array has duplicate values, we can find out where it was last seen. 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 comes up in discussions with Javascript engineers. There is nothing to be afraid of. This can be done in a single line of code using the.reduce() method. Let’s examine 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 shown you 13 JavaScript array-related tips and tips that can help you code and keep your code clean. Also, keep in mind that there are many tricks you can use in Javascript that are worth exploring, not just with arrays, but with different data types. I hope you enjoy the solutions presented in this article and will use them to improve your development process.

Have a good code together!

Dev. To /duomly/13-u…