some(), every(), reduce() methods in JS

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

Type: array.some( function ( item, index, arr) {} ,thisValue)

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

  • If one element satisfies the condition, the expression returns true, and the remaining elements will not be checked again.
  • Returns false if there is no element that satisfies the condition.

Note: some() does not check for empty arrays.

Note: some() does not mutate the original array.

const blobs = [
  "application/x-download",
  "application/vnd.ms-excel",
  "application/msword",
  "application/octet-stream",
];

request.interceptors.response.use(async (response, request) => {
  const contentType = response.headers.get("Content-Type");

  const isBlob = blobs.some((item) => contentType?.includes(item));

  if (isBlob) {
    request.responseType = "blob";
    return response;
  }
  
  const { error, code, status, msg, data } = await response.clone().json();

  if ((code === 200 || code === 202) && !error) return response;

  throw {
    response: {
      status: code || status,
      statusText: msg,
      data: data,
    },
  };
});

return request;
}

Second, there is every() method, which is the opposite of some() method

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

语法:array.every( function ( item, index, arr) {} ,thisValue)

The every() method checks 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 are not checked.

Returns true if all elements satisfy the condition.

Note: every() does not check for empty arrays.

Note: every() does not mutate the original array.

const list = [10, 12, 8, 12];
if (list.every((number) => number > 9)) {
   //代码块
}
//因为8小于9   所以返回false

3. reduce() method

Receives a function as an accumulator, and each value in the array (from left to right) is initially reduced and finally computed to a value. 

语法:array.reduce( function( total, currentValue, currentIndex, arr ),  initialValue )

array .reduce(callback,[initialValue])
reduce executes the callback function for each element in the array in turn, excluding elements that are deleted or have never been assigned a value in the array, accepting four parameters: initial value (or last callback function return value), the current element value, the current index, the array on which reduce was called. 

callback (function to execute for each value in the array, with four parameters)

    1. previousValue (the value returned by the last callback call, or the initial value provided (initialValue))
    2. currentValue (the element currently being processed in the array)
    3. index (the index of the current element in the array)
    4. array ( The array on which reduce is called)    
    initialValue (As the first argument to the first call to callback.)
 

Notice:

1. reduce() will not execute the callback function for an empty array.

2. When initialValue is provided, previousvalue is initialValue when the callback function is executed for the first time, and currentValue is the first item in the array; if no initial value is provided, previousvalue is the first item in the array, and currentValue is the second item in the array.

Common methods of reduce (preferably set default values)
1. Array summation, product

let numbers = [1, 2, 3, 4, 5]
let result1 = numbers.reduce((sum, n) => sum + n, 0)
console.log(result1); // 15
 
// let result2 = numbers.reduce((sum, n) => sum * n)
let result2 = numbers.reduce((sum, n) => sum * n, 1)
console.log(result2); // 120


2. Accumulate the value of the objects in the array

let numberObj = [{n: 1}, {n: 2}, {n: 3}, {n: 4}, {n: 5}]
let result3 = numberObj.reduce((sum, obj) => sum + obj.n, 0)
console.log(result3); // 15


3. Count the number of occurrences of each element in the array

let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple', 'red']
let countColor = colors.reduce(function(allColors, color){
    if(color in allColors) {
        allColors[color]++;
    } else {
        allColors[color] = 1;
    }
    return allColors;
}, {});
console.log(countColor); // {blue: 1, green: 1, indigo: 1, orange: 1, purple: 1, red: 2, yellow: 1}

4. Array deduplication

let arr = [1, 2, 3, 4, 4, 1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
        return pre.concat(cur)
    }else{
        return pre
    }
},[])
console.log(newArr); // [1, 2, 3, 4]


5. Convert two-dimensional array to one-dimensional array

let twoArray = [[0, 1], [2, 3], [4, 5]]
let oneArray = twoArray.reduce((arr, val) => arr.concat(val), [])
console.log(oneArray);  // [0, 1, 2, 3, 4, 5]


6. Convert multi-dimensional array to one-dimensional

let moreArr = [[0, 1], [2, 3], [4,[5,6,7]]]
const resultArr = function(moreArr){
      return moreArr.reduce((pre,cur) => pre.concat(Array.isArray(cur) ? resultArr(cur) : cur), [])
}
console.log(resultArr(moreArr)); // [0, 1, 2, 3, 4, 5, 6, 7]


7. Classify objects according to their attributes

let peopleInfo = [
    {name: 'aaa', age: 15, sex: '男'},
    {name: 'bbb', age: 16, sex: '女'},
    {name: 'ccc', age: 15, sex: '女'}
]
function groupBy(objectArray, property) {
    return objectArray.reduce((resultObj, obj) => {
        var key = obj[property]
        if(!resultObj[key]) {
            resultObj[key] = []
        }
        resultObj[key].push(obj)
        return resultObj;
    }, {})
}
let peopleAgeGroup = groupBy(peopleInfo, 'age')
console.log(peopleAgeGroup); // {15: [{name: "aaa", age: 15, sex: "男"}, {name: "ccc", age: 15, sex: "女"}],16: [{name: "bbb", age: 16, sex: "女"}]}
let peopleSexGroup = groupBy(peopleInfo, 'sex')
console.log(peopleSexGroup); // {男: [{name: "aaa", age: 15, sex: "男"}], 女: [{name: "bbb", age: 16, sex: "女"}, {name: "ccc", age: 15, sex: "女"}]}


references

1. The some() method in JS_js some_Shen Yicheng's Blog-CSDN Blog

2. Common methods of reduce()

3. JS array reduce() method detailed explanation and advanced skills_js reduce method returns data from the database to improve 'reduce' of undefined but write it yourself_12_12 ^^ DaDa's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_35624642/article/details/127203302