This is the sixth day of my participation in Gwen Challenge

Following the previous article, this one focuses on higher-order functions (array.reduce ()).

What is reduce?

  • The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value.

  • Reduce () can be used as a higher-order function for compose of functions.

  • grammar

    array.reduce(function(prev, cur, index, arr), init)

    • Prev (the value returned from the last call to the callback, or the initialValue provided)

    • Cur (the current element in the array being processed)

    • Index (index of the current element in the array)

    • Arr (Array of calls)

    • Init (the initial value passed to the function)

    • If an initial value is passed in, the first iteration of accumulator is the initial value; otherwise, it is the first element of the array. Subsequent iterations will be the result of the last iteration function. So, if the length of the array is n, if you pass in the initial value, the number of iterations is n; Otherwise, n minus 1.

    • For example, implement the array arr = [1,2,3,4] and find the sum of arrays

let arr = [1.2.3.4];
arr.reduce(function(pre,cur){return pre + cur}); // return 10
Copy the code
  • Browser Support

Common usage of reduce

  • Reduce accumulation
// with an initial value
var arr = [1.2.3.4]
var sum = arr.reduce((pre, item) = > {
    return pre + item
}, 10)
console.log(sum) / / 20

// No initial value
var arr = [1.2.3.4]
var sum = arr.reduce((pre, item) = > {
    return pre + item
},)
console.log(sum) / / 10
Copy the code
  • Reduce array deduplication
var arr = [1.2.3.3.2.1.4]
arr.reduce((acc, cur) = > {
  if(! (acc.includes(cur))) { acc.push(cur) }return acc
}, [])
// [1, 2, 3, 4]
Copy the code
  • Reduce calculates the maximum number of array items
var arr = [1.2.3.4];
arr.reduce((prev, cur) = > {
    return Math.max(prev,cur);
});
/ / 4
Copy the code
  • Reduce transforms a two-dimensional array into a one-dimensional array
var arr = [[1.2], [3.4], [5.6]]
arr.reduce((acc, cur) = > {
  return acc.concat(cur)
}, [])
/ / [6]
Copy the code
  • Attribute summation in reduce objects
var arr = [
    {subject: 'Math'.score: 90},
    {subject: 'Chinese'.score: 90},
    {subject: 'English'.score: 100}
]
arr.reduce((pre, cur) = > {
    return cur.score + pre
}, 0)
/ / 280
Copy the code
  • Reduce counts the number of occurrences of each element in the array
var arr = [1.2.3.3.2.1.2.1]
arr.reduce((acc, cur) = > {
  if(! (curin acc)) {
    acc[cur] = 1
  } else {
    acc[cur] += 1
  }
  return acc
}, {})
//{1: 3, 2: 3, 3: 2}
Copy the code
  • Reduce classifies arrays by attributes
var arr = [
    {subject: 'Math'.score: 90},
    {subject: 'Chinese'.score: 90},
    {subject: 'English'.score: 100},
    {subject: 'Math'.score: 80},
    {subject: 'Chinese'.score: 95}]; arr.reduce((acc, cur) = > {
  if(! acc[cur.type]) { acc[cur.type] = []; } acc[cur.type].push(cur)return acc
}, {})
Copy the code
  • Reduce implementation map
var arr = [1.2.3.4]
Array.prototype.reduceMap = function(callback) {
  return this.reduce((acc, cur, index, array) = > {
    const item = callback(cur, index, array)
    acc.push(item)
    return acc
  }, [])
}
arr.reduceMap((item, index) = > {
  return item + index
})
// [1, 3, 5, 7]

Copy the code
  • Reduce implementation forEach
var arr = [1.2.3.4]
Array.prototype.reduceForEach = function(callback) {
  this.reduce((acc, cur, index, array) = > {
    callback(cur, index, array)
  }, [])
}

arr.reduceForEach((item, index, array) = > {
  console.log(item, index)
})
/ / 1234
/ / 0123
Copy the code
  • Reduce implementation filter
var arr = [1.2.3.4]
Array.prototype.reduceFilter = function (callback) {
   return this.reduce((acc, cur, index, array) = > {
    if (callback(cur, index, array)) {
      acc.push(cur)
    }
    return acc
  }, [])
}
arr.reduceFilter(item= > item % 2= =0) // Filter out even entries.
/ / (2, 4]
Copy the code
  • Reduce implementation the find
var arr = [1.2.3.4]
var obj = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }]
Array.prototype.reduceFind = function (callback) {
  return this.reduce((acc, cur, index, array) = > {
    if (callback(cur, index, array)) {
      if (acc instanceof Array && acc.length == 0) {
        acc = cur
      }
    }    
    if ((index == array.length - 1) && acc instanceof Array && acc.length == 0) {
      acc = undefined
    }
    return acc
  }, [])
}
arr.reduceFind(item= > item % 2= =0) / / 2
obj.reduceFind(item= > item.a % 2= =0) // {a: 2}
obj.reduceFind(item= > item.a % 9= =0) // undefined
Copy the code

Important usage of reduce

  • Convert an array to an object
  • In real business development, you may have encountered situations where a background interface returns an array type and you need to convert it to an object that looks up each item of the array as a value based on the id value as a key.

Such as:

const peopleArr = [
  {
    id: 1.username: 'limei'.sex: 0.email: '[email protected]'
  },
  {
    id: 2.username: 'ajerry'.sex: 1.email: '[email protected]'
  },
  {
    id: 3.username: 'jnancy'.sex: 0.email: ' '}];function keyByUserReducer(acc, person) {
    return{... acc, [person.id]: person}; }const userObj = peopleArr.reduce(keyByUserReducer, {});
console.log(userObj);
Copy the code
  • Run asynchronous functions sequentially
  • Another thing we can do reduce() is to run Promises sequentially (not in parallel). If you have a rate limit on API requests, or if you need to pass the results of each PRMISE to the next promise, Reduce can help you
function fetchMessages(username) {
 return fetch(`https://example.com/api/messages/${username}`)
  .then(response= > response.json());
}

function getUsername(person) {
 return person.username;
}

async function chainedFetchMessages(p, username) {
 // In this function, p is a promise. We wait for it to finish,
 // then run fetchMessages().
 const obj = await p;
 const data = await fetchMessages(username);
 return { ...obj, [username]: data};
}

const msgObj = userList
 .map(getUsername)
 .reduce(chainedFetchMessages, Promise.resolve({}))
 .then(console.log);
// {glestrade: [...] , Mholmes: [...] Iadler: [...] }
Copy the code
  • The async function returns a Promise object, and callbacks can be added using the then method. When a function executes, it returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body.

  • Note that here we pass Promise as the initial promise.resolve (), and our first API call will run immediately.

  • Koa’s source code, there is a only module, the entire module is a simple return reduce method operation object:

var only = function(obj, keys){
 obj = obj || {};
 if ('string'= =typeof keys) keys = keys.split(/ +/);
 return keys.reduce(function(ret, key){
  if (null == obj[key]) return ret;
  ret[key] = obj[key];
  return ret;
 }, {});
};
Copy the code
  • By understanding the concept of reduce, this module mainly wants to create and return an object object with keys in obJ object.
var a = {
  env : 'development'.proxy : false.subdomainOffset : 2
}
only(a,['env'.'proxy'])  // {env:'development',proxy : false}
Copy the code
  • The above is to introduce to you detailed solution JS array Reduce() method detailed solution and advanced skills, I hope to help you