Arrays are an important and common knowledge in Javascript, and we often store data in arrays. As a Javascript engineer, arrays must be comfortable to use. In this article, we will show you how to learn about arrays in your daily development. Let’s get started!

1. Go to heavy

This is also a common interview question, how to JS array deduplicate. In the days of ES6, there was a very quick and easy way to use new Set() and array.from () or the expansion operator (…).

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

2. Replace

The array.prototype.splice method is used when you need to replace or delete specified data. The first parameter is the index to start with, the second parameter is the number to delete, and all that remains is the value to add (which can be one or more).

Var fruits = [" banana ", "apple", "orange", "watermelon", "orange", "grape", "apple"]; Fruits. Splice (0, 2, "potato", "tomato"); console.log(fruits); Returns [" potato ", "tomato", "orange", "watermelon", "apple", "orange", "grape", "apple"] copy the codeCopy the code

3. Go through the number groups

The most common method we use is the.map method for arrays, but there’s another method that does the same thing, and it’s not as popular, so we tend to ignore it: array.from

Var friends = [{name: 'John', age: 22}, {name: 'Peter', age: 23}, {name: 'Mark', age: 24}, {name: 'Maria', age: 24} 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"] duplicate codeCopy the code

4. Empty the array

Sometimes we need to empty an array, such as when the user clicks to empty the shopping cart. It can be deleted one by one, but few programmers are so cute, haha. In fact, this can be done in one line of code, which is to set the length to 0

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

5. Convert arrays to objects

Sometimes you need to convert an array to an object. Using iterative methods like.map() can do this, but there’s a faster way to do it if you want the key of the object to be the index of the array

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

6. Populate the array

When creating an array, have you ever encountered a situation where you need to fill in the default values, the first thing you’ll think of is looping through the array. ES6 provides a more convenient.fill method

Var newArray = newArray (10).fill(" 1 "); console.log(newArray); / / returns [" 1 ", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"] to copy codeCopy the code

7. Merge arrays

Do you know how to merge arrays? The answer is.concat(). Haha, but today’s story is about the ES6 expansion operator (…)

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"] duplicate codeCopy the code

8. Intersection of two arrays

Find the intersection of two arrays is a classic JS interview question, this question can be a good test candidate’s logic is clear, to the array master is skilled. There are many answers to this question, but here is a short version of ES6

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); // Returns [2, 4, 6] copy codeCopy the code

9. Eliminate false values

So first of all, what are falsy values? In JS, false values are: false, 0, “, null, NaN, undefined. Now we find these false values and remove them, using the.filter method

Var mixedArr = [0, "blue", "NaN", 9,trueUndefined, "white",false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); / / returns [9, "blue",true, "white"] copies the codeCopy the code

The random value

Fetching a random value from an array is also a classic interview question. Generate a random value x: x >= 0 and x < array length

Var colors = "blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown"]. Var randomColor = colors[(math.floor (math.random () * (colors.length))))] copies the codeCopy the code

11. A reverse order

How do I reverse an array? All it takes is one line of code

Var colors = "blue", "white", "green", "navy", "pink", "purple", "orange", "yellow", "black", "brown"]. var reversedColors = colors.reverse(); / / or colors. Slice (). The reverse (); // What's the difference? console.log(reversedColors); / / returns [" brown ", "black", "yellow", "orange", "purple", "pink", "navy" and "green", "white", "blue"] to copy codeCopy the code

12.lastIndexOf()

A lot of times we look for elements in an array. IndexOf is often used, and lastIndexOf is often ignored. One of the scenarios where the lastIndexOf is used is when there is duplicate data in an array.

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 codeCopy the code

13. Sum

Sum up all the elements in the array. There are many answers. All roads lead to Rome. Reduce is used here.

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

conclusion

In fact, in daily development, it is likely to encounter more complex business, I hope you can be dissected into small problems one by one, to find the place to start. Come on guys!

The original link


Author: Xiaohua resolutely on the king


Link: https://juejin.cn/post/6844904067446079496


Source: Nuggets


Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.