This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

The purpose of this series of interviews is to learn the basics so that you can easily solve the various forms of the exam. This article covers some of the higher-order functions in JavaScript, including parameters and return values.

What is a higher-order function?

Higher-order functions are functions that operate on other functions, taking them as arguments or returning them.

Simply put, a higher-order function is a function that takes a function as an argument or returns a function as output.

1. Functions can be arguments

function bar(fn){
    if(typeof fn === "function"){
        fn()
    }
}
/ / call
bar(function () {})
Copy the code

2. Functions can be returned as values

function bar(){
    return function (){}}/ / call
const fn = bar ()
console.log(fn)
Copy the code

Higher-order functions in JS

1.map

  • map()Returns a new array whose elements are the values processed by the original array call function.
  • map()Empty arrays are not checked.
  • map()It doesn’t change the original array.

The callback function passed to the map() method takes three arguments: currentValue, index, and array.

  1. currentValue:Must be. The value of the current element.
  2. index:optional. The index of the current element.
  3. arr:optional. The array object to which the current element belongs.

Having such an array [10,20,45,50,65,150,70,40] now has the following requirements

Take all the elements in the array * 2.

let arr = [10.20.45.50.65.150.70.40];
let newArr = arr.map((item) = > {
  return item * 2;
});
console.log(newArr)// [20, 40, 90, 100, 130, 300, 140, 80]
Copy the code

2.filter

  • filter()The new array () method creates a new array by checking all the elements in the specified array that match the criteria.
  • filter()Empty arrays are not checked.
  • filter()It doesn’t change the original array.

The callback function passed to the filter() method takes three arguments: currentValue, index, and array.

  1. currentValue:Must be. The value of the current element.
  2. index:optional. The index of the current element.
  3. arr:optional. The array object to which the current element belongs.

Having such an array [20, 40, 90, 100, 130, 300, 140, 80] now has the following requirements

Returns all elements in the array less than 100.

 let arr = [20.40.90.100.130.300.140.80];
let newArr = arr.filter((item) = > {
  return item < 100;
});
console.log(newArr);/ / [20, 40, 90, 80]
Copy the code

3.forEach

  • forEach()The method is similar tomap(), the function passed in does not return a value and passes the element to the callback function.
  • forEach()Callbacks are not executed for empty arrays.
  • forEach()Does not return a new array, always returns undefined.

The callback function passed to the forEach() method takes three arguments: currentValue, index, and array.

  1. currentValue:Must be. The value of the current element.
  2. index:optional. The index of the current element.
  3. arr:optional. The array object to which the current element belongs.

Having such an array [20, 40, 90, 100] now has the following requirements.

Prints the elements in the array and their indexes separately.

let arr = [20.40.90.100];
let newArr = arr.forEach((item,index) = > {
  console.log(item,index);
});
/ / 20 0
/ / 40 1
2 / / 90
3 / / 100
Copy the code

4.sort

  • sort()The sort () method is used to sort the elements of an array.
  • sort()Will modify the original array.

The sort() method takes an optional argument that specifies the sort order and must be a function.

If no argument is passed, the sort() method defaults to converting all elements to String and then sorting by ASCII.

If you want to sort by other criteria, you need to provide a comparison function that compares two values and then returns a number indicating the relative order of the two values. The comparison function should take two arguments, a and b, and return the following values:

  • ifaLess thanb, in the sorted arrayaShould appear atbBefore, returns a less than0The value of the.
  • ifaIs equal to theb, the return0.
  • ifaIs greater thanb, returns a greater than0The value of the.

Having such an array [10, 20, 1, 2] now has the following requirements

In order from smallest to largest.

let arr = [10.20.1.2];
arr.sort(function (x, y) {
    if (x < y) {
        return -1;
    }
    if (x > y) {
        return 1;
    }
    return 0;
});
console.log(arr); // [1, 2, 10, 20]
Copy the code

In order from largest to smallest

let arr = [10.20.1.2];
arr.sort(function (x, y) {
    if (x < y) {
        return 1;
    }
    if (x > y) {
        return -1;
    }
    return 0;
}); // [20, 10, 2, 1]
Copy the code

5.some

  • some()The array_test () method checks whether an element in an array satisfies a specified condition.
  • some()Method executes each element of the array in turn.
  • If one element satisfies the condition, the expression returnstrueThe remaining elements will not be tested.
  • Returns if no element satisfies the conditionfalse
  • some()Empty arrays are not checked.
  • some()It doesn’t change the original array.

The callback function passed to the some() method takes three arguments: currentValue, index, and array.

  1. currentValue:Must be. The value of the current element.
  2. index:optional. The index of the current element.
  3. arr:optional. The array object to which the current element belongs.

Having such an array [10, 20, 1, 2] now has the following requirements.

Check if the array contains numbers greater than 10.

let arr = [10.20.1.2];
let result = arr.some((item) = > {
  return item > 10;
});
console.log(result);//true
Copy the code

6.every

  • every()The method checks whether all elements of an array match the specified condition.
  • every()Method executes each element of the array in turn.
  • If one element in the array is detected to be unsatisfied, the entire expression is returnedfalseAnd the remaining elements will not be detected.
  • Returns if all elements meet the criteriatrue.
  • every()Empty arrays are not checked.
  • every()It doesn’t change the original array.

The callback passed to the every() method takes three arguments: currentValue, index, and array.

  1. currentValue:Must be. The value of the current element.
  2. index:optional. The index of the current element.
  3. arr:optional. The array object to which the current element belongs.

Having such an array [11, 20, 51, 82] now has the following requirements.

Check whether all numbers in the array are greater than 10.

let arr = [11.20.51.82];
let result = arr.every((item) = > {
  return item > 10;
});
console.log(result);//true
Copy the code

7.reduce

  • reduce()Method receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value.
  • reduce()Callbacks are not executed for empty arrays.

The reduce method takes two parameters

  • The callback function

  • An optional initialValue. If the second parameter initialValue is not passed, the first execution of the function returns the first element in the array as a prev parameter.

The callback function passed to the reduce() method takes four arguments: prev, current, currentIndex, arR.

  1. prev:Must be. The initial value passed in by the function or the return value from the previous callback.
  2. current:Must be. The value of the element currently being processed in the array.
  3. currentIndex:optional. Current element index.
  4. arr:optional. The array to which the current element belongs.

Having such an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] now has the following requirements

Returns the sum of all elements of an array

let arr = [1.2.3.4.5.6.7.8.9.10];
let sum = arr.reduce((prev, current) = > {
  return prev + current;
}, 0);
console.log(sum); / / 55
Copy the code

8.reduceRight

The function of the reduceRight() method is the same as that of reduce(), except that reduceRight() adds the items in the array forward from the end of the array.

9.find

  • find()Method is used to find the first element that matches the criteria, and if it is found, returns the element, otherwise returnsundefined.
  • find()Empty arrays are not checked.
  • find()It doesn’t change the original array.

The callback passed to the find() method takes three arguments: currentValue, index, and array.

  1. currentValue:Must be. The value of the current element.
  2. index:optional. The index of the current element.
  3. arr:optional. The array object to which the current element belongs.

Having such an array [11, 20, 51, 82] now has the following requirements

Returns the first element in the array greater than 50

let arr = [11.20.51.82];
let result = arr.find((item) = > {
  return item > 50;
}, 0);
console.log(result);/ / 51
Copy the code

10.findIndex

Findindex () is similar to find() in that it looks for the first element that matches the criteria, except that findIndex () returns the index of the element, or -1 if none is found.

Having such an array [11, 20, 51, 82] now has the following requirements.

Returns the index of the first element in an array greater than 50.

let arr = [11.20.51.82];
let result = arr.findIndex((item) = > {
  return item > 50;
}, 0);
console.log(result);/ / 2
Copy the code

Chain calls to higher-order functions

Suppose you have an array [10, 20, 45, 50, 65, 150, 70, 40]

Requirement 1: Give each element in the array * 2

We use map() and get [20, 40, 90, 100, 130, 300, 140, 80]

Requirement 2: Return all elements less than 100 of the new array obtained from requirement 1

We use filter() and get [20, 40, 90, 80]

Requirement 3: Calculate the sum of all elements of the new array obtained in requirement 2

We used reduce() and we got 230

We can call the above three functions in chain order to get the final result

let arr = [10.20.45.50.65.150.70.40];
let total = arr.map(n= > n * 2).filter(n= > n < 100).reduce((pre, n) = > pre + n);
console.log(total);/ / 230
Copy the code