This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge
JavaScript is full of tricks. JavaScript is a huge language with a set of sometimes strange features that make it special and different. There are many ways to get things done in JavaScript; Especially for one of the most important concepts in the programming world, arrays. Today, we’re going to review a series of interesting and useful tricks for using arrays in JavaScript.
Removes duplicates from an array
This is a very popular interview question about Javascript arrays, how to extract unique values from Javascript arrays. Here are two quick and easy solutions to this problem.
👉 : Array. From (new Set(arR)); 👉 : [...new Set(ARR)];Copy the code
Replaces a specific value in an array
Sometimes you need to replace specific values in an array when you create code, and there’s a nice short way to do that, but you may not know it yet.
We can use.splice(start, value to remove,….. , valueToAdd)
-
[start] specifies where we want to start [add/remove] (if negative, from the end of the array)
-
【value to remove】 Number of items to be removed
-
[….., valueToAdd] and new items added to the array
Positive 👉arr1.splice(0, 2, "Hi", "good"); Negative 👉arr2.splice(-1, 2, "Hi", "good");Copy the code
If you want to replace a specified value
For example, if we want to replace “ah” with “oh” in the next example, we can do this
Var Arr = [' you ',' ok ',' ah ','!']; Let replaceIndex = arr.indexof (" ah "); If (replaceIndex > -1) {Arr[replaceIndex] = ""; } console.log(Arr)Copy the code
Object to Array
Use the.from() method to quickly convert an object property into an array
var friendsNames = Array.from(friends, ({name}) => name);
Copy the code
Convert an array into an object
If we have an array and we need to convert it to an object containing the data, we can use the extension operator (…) To do so
var arrObj = { ... arr };Copy the code
Fill the array with data
When we create an array, there are cases where we want to fill it with some data, or we need an array with the same value, in which case the.fill() method provides a simple and clean solution.
var newArray = new Array(5).fill("Axjy");
Copy the code
Merge array
Do you know how to merge an array into one without using the.concat() method?
An easy way to combine any number of arrays into a single line of code is to use the extension operator (…) .
var arr = [...arr1,...arr2,...arr3]
Copy the code
Find the intersection of two arrays
This is also one of the most popular challenges you may 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 the method shown earlier in this article to ensure that the values in the array we are examining are not duplicate;
We will use the.filter and.includes methods. As a result, we get an array of values that exist in both arrays.
var duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item));
Copy the code
Remove false values from array (*)
First, let’s define false values. In Javascript, false values are false, 0, “”, null,NaN, undefined. We can use the.filter() method to filter these false values.
var trueArr = mixedArr.filter(Boolean);
Copy the code
Get a random value from an array
Sometimes we need to randomly select a value from an array. To create it in a simple, quick, and short manner and to keep our code clean, we can get a random index number based on the array length.
var ArrItem = Arr[(Math.floor(Math.random() * (Arr.length)))]
Copy the code
You can also do an encapsulation
Array.prototype.random = function () { return this[Math.floor(Math.random() * this.length)]; } : [1, 2, 19, 769].random()Copy the code
Inversion array
When we need to flip our array, instead of having to go through complicated loops and functions to create it, there’s a simple array method that we can flip our array with just one line of code.
It’s going to change the array
var reversedArrs = Arr.reverse();
Copy the code
I’m not going to change the way I wrote the array
var reversedArrs = [...Arr].reverse();
Copy the code
The lastIndexOf () method
In Javascript, there is an interesting way to find 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.
var lastIndex = nums.lastIndexOf(5);
Copy the code
Sum all the values in the array
This is a common question in interviews for Javascript engineers. It can be resolved in a single line of code using the.reduce method
var sum = nums.reduce((x, y) => x + y);
Copy the code
You can also subtract or multiply all values
var sub = nums.reduce((x, y) => x - y);
var mul = nums.reduce((x, y) => x * y);
Copy the code
Empty array
To empty an array, you can use one of these schemes
-
Direct assignment is null
-
Length is changed to 0
-
Splice method
-
The pop method
Arr = [] Arr.length = 0; Arr.splice(0); while (Arr.length > 0) { Arr.pop(); } Copy the code
Find the maximum array value
To find the maximum value in an array of numbers, we can do this
let max = Math.max(... numbers);Copy the code
Find the array minimum value
We can use min to find the minimum. We also use the extension operator above. Let’s use another one
let min = Math.min.apply(null, numbers);
Copy the code
So apply is passing in an array
conclusion
In this article, I’ve shown you 15 tips and tricks that I hope will help you code and keep your code clean and concise. In addition, there are many different tricks worth exploring in Javascript that involve not only arrays but also different data types. If you have a better idea, please leave a comment.
Reference:
13 useful JavaScript array tips and tricks you should know
Leave a like if you get something! 😘