Higher order function - make the code simpler and include examples

Posted by Grant Holmes on Sat, 26 Feb 2022 10:05:04 +0100

The arrow function is used in this article. If you don't know, you can check it 👇

ES6 study noteshttps://blog.csdn.net/TeAmo__/article/details/123053529?spm=1001.2014.3001.5501

catalogue

forEach traversal

filter filtering

Find find

findIndex find subscript

map mapping

reduce accumulation

Some some

every all

Sort sort

forEach traversal

Is essentially the same as for
For an empty array, the callback function will not be executed.
Do not change the original array, no return value
You can use return; Implement continue
break cannot be used;

eg: use return; Then implement continue in forEach

Three parameters in the callback function: the current item traversed by item; Current index of index traversal; self traverses the array itself

    var arr = [1, 2, 3, 4, 5];
    arr.forEach((item, index, self) => {
        if (item === 3) {
            return;
        }
        console.log(item, index, self);
    });

 

filter filtering

Non null array detection
Do not change the original array
The return value is a new array that meets the filtering conditions
When return is true, the current element is output

eg: find the intersection of two arrays

    var arr1 = [1, 2, 3];
    var arr2 = [2, 3, 4];
    var arr_j = arr1.filter(item => arr2.includes(item));
    console.log("intersection:", arr_j);//Intersection: (2) [2, 3]


Find find

Do not execute on empty arrays
Returns the first element that meets the condition
undefined if none
Do not change the original array

eg: find the first number and subscript greater than 50

    var arr = [9, 10, 29, 0, 58, 100, 1];
    var num = arr.find(item => item > 50);
    var ind = arr.findIndex(item => item > 50);
    console.log(num);//58
    console.log(ind);//4

 

findIndex find subscript

Consistent with the characteristics of find, the first subscript satisfying the condition is returned

See the code above for an example

map mapping

The return value is a new array
The elements in the new array are the values of the corresponding original array after function processing
Do not detect empty arrays
Do not change the original array

Example 1: convert array [,,] into object [{}, {}, {}]

    // Change the array urls to pics
    // var urls = ["https://dwz.cn/f2Jy4YZz","https://dwz.cn/pkShASrA","https://dwz.cn/5aBs4Tyn"] 
    // Change to
    // pics=[{pic:"https://dwz.cn/f2Jy4YZz"},{pic:"https://dwz.cn/pkShASrA"},{pic:"https://dwz.cn/5aBs4Tyn"}]
    var urls = ["https://dwz.cn/f2Jy4YZz", "https://dwz.cn/pkShASrA", "https://dwz.cn/5aBs4Tyn"];
    console.log(urls);
    var pics = urls.map(item => ({
        "pic": item
    }));
    console.log(pics);

Example 2: form the ages in the object array into a new array

    var arr = [{
            name: 'Xiao Ming',
            age: 16,
            sex: 'male'
        },
        {
            name: 'Xiao Hong',
            age: 17,
            sex: 'female'
        },
        {
            name: 'Xiaobai',
            age: 18,
            sex: 'female'
        },
    ]
    var age = arr.map(item => item.age);
    console.log(age);//(3) [16, 17, 18]

 

reduce accumulation

The reduce() method receives a function as an accumulator. Each value in the array (from left to right) is reduced and finally calculated as a value.
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total is required. Initial value, or return value after calculation.
currentValue = required. Current element
currentIndex is optional. Index of the current element
arr = optional. The array object to which the current element belongs.

eg: summation function

    function add(...arg) {
        return arg.reduce((a, b) => a + b);
    }
    console.log(add(1, 2, 3));//6
    console.log(add(1, 2, 3, 4, 5));//15

 

Some some

The some() method is used to detect whether the elements in the array meet the specified conditions (provided by the function).

The some() method executes each element of the array in turn:

If one element meets the condition, the expression returns true, and the remaining elements will not be detected.
If there is no element that meets the condition, false is returned.

some() does not detect empty arrays.

some() does not change the original array.

eg: judge whether one of the array is older than 16 years old and whether all are younger than 60 years old

    var computers = [{
            name: "Apple",
            age: 8
        },
        {
            name: "IBM",
            age: 12
        },
        {
            name: "Acer",
            age: 32
        },
    ];
    var isHas = computers.some(item => item.age > 16);
    var isAll = computers.every(item => item.age < 60);
    console.log("Is there one older than 16:" + isHas);//true
    console.log("Are all under 60 years old:" + isAll);//true


every all


The every() method is used to detect whether all elements of the array meet the specified conditions (provided by the function).

The every() method detects all elements in the array using the specified function:

If an element in the array is detected to be unsatisfactory, the entire expression returns false and the remaining elements will not be detected.
Returns true if all elements meet the criteria.

every() does not detect empty arrays.

every() does not change the original array.

See the code above for an example


Sort sort


The sort() method is used to sort the elements of the array.

The sort order can be alphabetic or numeric, in ascending or descending order.

The default sort order is ascending alphabetically.

Note: when the numbers are arranged in alphabetical order, "40" will come before "5".

To use numeric sorting, you must call a function as an argument.

The function specifies whether numbers are arranged in ascending or descending order.

Change the original array!

Example 1: array sorting

    var arr1 = [1, 12, 15, 33, 7, 9];
    arr1.sort((a, b) => a - b);
    console.log(arr1); //[1, 7, 9, 12, 15, 33]

Example 2: sorting by age in object array

    var arr2 = [{
            name: 'Xiao Ming',
            age: 16,
            sex: 'male'
        },
        {
            name: 'Xiao Hong',
            age: 35,
            sex: 'female'
        },
        {
            name: 'Xiaobai',
            age: 18,
            sex: 'female'
        },
    ]
    arr2.sort((a, b) => a.age - b.age);
    console.log(arr2);

Operation results:

Give it a compliment 👍

Topics: Javascript Front-end ECMAScript