1. Sum all the values in the array

Var arr =,2,4,5,6 [1]; var newArr=arr.reduce((x,y) =>{x+y}) //18Copy the code

2. Reverse the array, using reverse

Var arr =,2,4,5,6 [1]; Var newArr = arr. Reverse () / /,5,4,2,1 [6]Copy the code

3. Get a random value from the array

Var arr =,2,4,5,6 [1]; var newArr=arr[(Math.floor(Math.random()*(arr.length)))] //"2"Copy the code

4. Delete virtual values from array :0,undefined,null, “”, “NaN,false — use filter method

Var arr = [" ", "', NaN, null, true, false, 0, 9]. var newArr=arr.filter(Boolean); //[true,9]Copy the code

5. To find the intersection of an array, first of all to ensure that the data in the data group is not repeated, in the use of the following denomination method for processing

Var arr1 = 4-trichlorobenzene [1]; Arr2 = (4 and 6); Var newArr = new Set (arr1) [...] filter (item = > {arr2. Includes (item)}) / / result: [4]Copy the code

6. Array merge — using the spread character (…) Merge arrays

Var arr1 = 4-trichlorobenzene [1]; Arr2 =[5,6,7] var newArr =[...arr1,...arr2]; / /,2,4,5,6,7 [1]Copy the code

7. Used for sorting object values in arrays – positive ordering

var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}]; var compare = function (prop) { return function (obj1, obj2) { var val1 = obj1[prop]; var val2 = obj2[prop]; if (val1 < val2) { return -1; } else if (val1 > val2) { return 1; } else { return 0; }}} to the console. The log (arr. Sort (compare (" age ")) / / result: [{name: "ZLW, age: 24}, {name:" WLZ ", the age: 25}]Copy the code

8. Used to sort object values in an array – in reverse order

var arr = [{name: "zlw", age: "24"}, {name: "wlz", age: "5"}]; var compare = function (prop) { return function (obj1, obj2) { var val1 = obj1[prop]; var val2 = obj2[prop]; if (! isNaN(Number(val1)) && ! isNaN(Number(val2))) { val1 = Number(val1); val2 = Number(val2); } if (val1 < val2) { return -1; } else if (val1 > val2) { return 1; } else { return 0; }}} to the console. The log (arr. Sort (compare (" age "))) / / result: [{name: "WLZ", the age: "5"}, {name: "ZLW", the age: "24"}]Copy the code