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 (…).

varFruits = [" banana ", "apple", "orange", "watermelon", "apple", "orange", "grape", "apple");/ / method
var uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits); Returns [" banana ", "apple", "orange", "watermelon", "grape"]
/ / method 2
varUniqueFruits2 = [...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).

varFruits = [" 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 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: 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

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 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

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

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 = new Array(10). The 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 merge arrays? The answer is.concat(). Haha, but today’s story is about the ES6 expansion operator (…)

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. 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 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 = [0And "blue", "",NaN.9.true.undefined"White",false];
var trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // Returns [" blue ", 9, true, "white"]
Copy 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

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

11. A reverse order

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

varColors = "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"]
Copy 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 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 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