2021, you must know the JS array skills

Array is one of the most common concepts in Javascript. It provides us with many possibilities to process data. It is necessary to be familiar with some common operations of array. js array method

When we learn about arrays in js, we will be exposed to some methods of arrays in js. For us, these methods can easily traverse to achieve the results we want. However, because there are many methods, some methods are not commonly used, and may be forgotten after a period of time. Here, I have sorted out the methods of 21 arrays for your reference.

Method nameCorresponding versionfunctionWhether the original array is changed
concat()ES5-Merge arrays and return the merged datan
join()ES5-Use the delimiter to convert the array to a string and returnn
pop()ES5-Delete the last bit and return the deleted datay
shift()ES5-Delete the first bit and return the deleted datay
unshift()ES5-Add one or more data in the first bit and return the lengthy
push()ES5-Add one or more data in the last bit and return the lengthy
reverse()ES5-Invert the array and return the resulty
slice()ES5-Intercepts the array at the specified location and returnsn
sort()ES5-Sorting (character rule), return resultsy
splice()ES5-Delete the specified location, replace it, and return the deleted datay
toString()ES5-Convert directly to a string and returnn
valueOf()ES5-Returns the original value of an array objectn
indexOf()ES5Query and return the index of the datan
lastIndexOf()ES5Reverse query and return the index of the datan
forEach()ES5The parameter is a callback function, which will traverse all items of the array. The callback function accepts three parameters, namely value, index and self; forEach has no return valuen
map()ES5The same as forEach, the callback function returns data at the same time to form a new array, which is returned by mapn
filter()ES5The same as forEach, and the callback function returns a Boolean value. The data that is true forms a new array, which is returned by the filtern
every()ES5The same as forEach, the callback function returns Boolean values, all of which are true, and every returns truen
some()ES5The same as forEach, the callback function returns a Boolean value. As long as one is true, some returns truen
reduce()ES5Merge, the same as forEach, iterates over all items of the array and constructs a final value, which is returned by reducen
reduceRight()ES5Reverse merge, the same as forEach, iterates over all items of the array and constructs a final value, which is returned by reduceRightn

The following are common operations for arrays

1. Array de duplication

1. from() superimposes the new Set() method

The from method can be directly used for the de duplication of string or numeric array.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var uniquePlants = Array.from(new Set(plants)); 
console.log(uniquePlants); // [ 'Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Mars', 'Jupiter' ]
2. spread operator (...)

Extension operator is a major innovation of ES6 and has many powerful functions.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var uniquePlants = [...new Set(plants)]; 
console.log(uniquePlants); // [ 'Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Mars', 'Jupiter' ]

2. Replace a specific value in an array

The splice() method adds / removes items to / from the array, and then returns the deleted items. This method changes the original array. Special attention should be paid to the position of the inserted value!

// arrayObject.splice(index,howmany,item1,.....,itemX)

var plants = ['Saturn', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var result = plants.splice(2, 1, 'www.shanzhonglei.com')
console.log(plants); // ['Saturn','Uranus','www.shanzhonglei.com','Mercury','Venus','Earth','Mars','Jupiter']
console.log(result); // ['Mercury']

3. There is no mapping array for map()

Let's first introduce the map method. The map() method returns a new array. The elements in the array are the values of the original array elements after calling the function. It will process the elements in order of the original array elements. Note: map() does not change the original array, nor does it detect empty arrays.
Let's implement an array mapping without a map:

// array.map(function(currentValue,index,arr), thisValue)

var plants = [
    { name: "Saturn" },
    { name: "Uranus" },
    { name: "Mercury" },
    { name: "Venus" },
]
var plantsName = Array.from(plants, ({ name }) => name);
console.log(plantsName); // [ 'Saturn', 'Uranus', 'Mercury', 'Venus' ]

4. Empty array

If you want to empty an array, set the length of the array to 0. Well, this is a little simple.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
plants.length = 0;
console.log(plants); // []

5. Convert array to object

The fastest way to convert an array to an object is the spread operator (...).

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var plantsObj = {...plants }
console.log(plantsObj); // {'0': 'Saturn','1': 'Earth', '2': 'Uranus','3': 'Mercury','4': 'Venus','5': 'Earth','6': 'Mars','7': 'Jupiter'}

6. Fill array with data

If we need to fill the array with some data, or if we need a data with the same value, we can use the fill() method.

var plants = new Array(8).fill('8');
console.log(plants); // ['8', '8', '8','8', '8', '8','8', '8']

7. Merge array

Of course, you will think of the concat() method, but oh, the spread operator (...) is also very fragrant, which is another application of the extension operator.

var plants1 = ['Saturn', 'Earth', 'Uranus', 'Mercury'];
var plants2 = ['Venus', 'Earth', 'Mars', 'Jupiter'];
console.log([...plants1, ...plants2]); // ['Saturn', 'Earth','Uranus', 'Mercury','Venus', 'Earth','Mars', 'Jupiter']

8. Intersection of two arrays

The intersection of two arrays is required. First, ensure that the array is not repeated, and then use the filter() method and the includes() method.

var plants1 = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var plants2 = ['Saturn', 'Earth', 'Uranus'];
var alonePlants = [...new Set(plants1)].filter(item => plants2.includes(item));
console.log(alonePlants); // [ 'Saturn', 'Earth', 'Uranus' ]

9. Delete false values from the array

We often need to remove false values when processing data. In Javascript, false values are false, 0, "", null, NaN, undefined.

var plants = ['Saturn', 'Earth', null, undefined, false, "", NaN, 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
var trueArr = plants.filter(Boolean);
console.log(trueArr); // ['Saturn', 'Earth','Uranus', 'Mercury','Venus', 'Earth','Mars', 'Jupiter']

10. Gets the random value in the array

We can get a random index number based on the length of the array.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
console.log(plants[Math.floor(Math.random() * (plants.length + 1))])

11. lastIndexOf() method

lastIndexOf() can help us find the index of the last occurrence of an element.

var plants = ['Saturn', 'Earth', 'Uranus', 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter'];
console.log(plants.lastIndexOf('Earth')) // 5

12. Sum

Sum all the elements in the array. Ha ha, it's another interview question. There are also many answers. All roads lead to Rome. Reduce is used here. The reduce method is a knowledge point worth learning and is of great use

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

Change jobs? Looking for interview questions? Come to the front-end interview question bank wx to search the advanced front-end

Tags: Javascript Front-end ECMAScript

Posted on Tue, 26 Oct 2021 04:49:29 -0400 by corsc