13 Useful JavaScript array tips and tricks you should know

Arrays are one of the most common concepts in JavaScript, and they open up a lot of possibilities for internal data storage in JavaScript. Considering that arrays are one of the most fundamental topics in JavaScript since the beginning of programming, in this article I will bring you some useful tips that you may not know! So let’s get started.

1. Remove duplicates from the array

How to extract a unique value from a JavaScript array is a very common JavaScript interview problem, and the quick and easy solution to this problem is to use the new Set() method. There are two ways to do this, either through.from() or by using the extension operator (…). .

var fruits = ["banana"."apple"."orange"."watermelon"."apple"."orange"."grape"."apple"]; Var uniqueFruits = array. from(new Set(fruits)); console.log(uniqueFruits); / / return ["banana"."apple"."orange"."watermelon"."grape"Var uniqueFruits2 = [... new Set(fruits)]; console.log(uniqueFruits2); / / return ["Banana","apple","orange","watermelon","grape"]
Copy the code

Isn’t that easy?

2. Replace the specified value in the array

Sometimes you need to replace the values specified in the array, and there is a simple way to do this that you may not know about. To do this, you can use.splice(start position, removed value, added value) and then pass in three parameters that specify where to start, how many values to change, and what new value to add.

var fruits = ["Banana","apple","orange","watermelon","apple","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. Do not use the. Map () mapping array

Everyone probably knows about the.map() method for arrays, but there’s a different solution that does a similar thing and has clean code that uses 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

Sometimes you need to empty an array of elements, but you don’t want to remove them one by one. You can do this very easily with one line of code. To clear the array, just set the length of the array to 0, and you’re done.

var fruits = ["Banana","apple","orange","watermelon","apple","orange","grape","apple"]; fruits.length = 0; console.log(fruits); / / return []Copy the code

5. Convert arrays to objects

Sometimes we happen to have an array, but for some purpose we need an object with data, and the fastest way is to use the extension operator (…). Convert arrays directly to objects.

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

6. Fill in the array

Sometimes we create an array and need to fill in some data, or we need an array with values. Fill () is easy.

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

7. Merge arrays

If you don’t use the.concat() method do you know how to combine multiple arrays into one? A simple way to combine any number of arrays into a single line of code. As you probably already know, the extension operator (…) This is useful for working with arrays, as well as in this scenario.

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 popular Javascript interview challenges, because it shows whether you can use array methods and what your logic is. To find the intersection of the two arrays, we will use the methods described earlier, and to ensure that there are no duplicates in the array checked, we will use the.filter and.includes methods. You end up with an array with values that are in both arrays. Check code:

var numOne = [0, 2, 4, 6, 8, 8]; var numTwo = [1, 2, 3, 4, 5, 6]; DuplicatedValues = [... new Set(numOne)]. DuplicatedValues = [... new Set(numOne)]. console.log(duplicatedValues); // Return [2, 4, 6]Copy the code

9. Remove falsy from array

First, define false values. In JavaScript, false values are false, 0, “”, null, NaN, undefined. Now to remove these values from the specified array, we use the.filter() method.

var mixedArr = [0, "blue"."", NaN, 9, true, undefined, "white".false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); / / return ["blue"And nine,true."white"]

Copy the code

10. Get random values from arrays

Sometimes we need to randomly select a value from an array. For a short, quick way to keep the code simple, we can get a random index value based on the length of the array. Look at the code:

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

11. Reverse the array

When we need to flip an array instead of having to create it through a complicated loop and function, there’s a simple array method that can do that, and flip an array with just one line of code. Here’s a check:

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

12.. lastIndexOf () method

In JavaScript, there is an interesting method that allows you to find the index value of the last occurrence of a given element. For example, if an array has a duplicate value, you can find its last occurrence.

var nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7]; var lastIndex = nums.lastIndexOf(5); console.log(lastIndex); / / returnCopy the code

13. Sum all the values in the array

This is another common challenge when interviewing development engineers, and it’s nothing to be afraid of. Reduce can be solved in one line of code:

var nums = [1, 5, 2, 6]; var sum = nums.reduce((x, y) => x + y); console.log(sum); / / return 14Copy the code

conclusion

In this article, I gave 13 tips to help you to write concise code, remember the same JavaScript and there are many worth exploring in different skills, not only about array, there are other data types, and I hope you will enjoy this article provides the solution, you can use them to improve the development process.

Happy coding!