reduce
- callback (a function called on each item in the array that takes four arguments:)
previousValue (the return value, or initial value, from the last call to the callback function)
currentValue (array element currently being processed)
currentIndex (array element subscript currently being processed)
Array (array calling reduce() method) - initialValue (optional initial value. As the value passed to previousValue when the callback function is called for the first time)
Search for concepts. Let's talk about what I met and understood. See the code
callback
//reduce as accumulator let arr = [1, 2, 3, 4, 5] let sum = arr.reduce((init, item, i, self) => { console.log(`init---${init}, item---${item}, i---${i}, self---${self}`) return init + item }) console.log(sum) //15
See the following figure for callback parameters
init defaults to the first item of the array, accumulates the items of the array once, and returns the last item.
Item loop array each item
i array subscript
self currently calls the reduce array itself.
initialValue
The optional initial value, as the default value of the first parameter of the callback function, is also the return value of each callback. See the code
let obj = { '/home': { meta: { title: 'home page' }, component: '@/page/home' }, '/question': { meta: { title: 'problem' }, component: '@/page/question' } } // Convert to array let map = [{ path: '/home', meta: { title: 'home page' }, component: '@/page/home' }, { path: '/question', meta: { title: 'problem' }, component: '@/page/question' }] let map1 = Object.keys(obj).reduce((arr, item) => { return (arr.push({ path: item, ...obj[item] }), arr) }, []) console.log(map1)
Effect after transformation
This chestnut came from the route configuration of vue, which was also optimized by several versions at that time.
Let's explain in detail
Object.keys(obj) //Convert obj to an array with contents of key reduce((arr,item)=>{ }) //The parameter has been explained above. The parameter after the callback []: the default value of the return value is an empty array //about return (arr.push({ path: item, ...obj[item] }), arr) //In fact, it can be written as arr.push({ path: item, ...obj[item] }) return arr
Please refer to: javascript comma operator
Don't worry. There's another usage just found.
//Requirement: judge whether the end of each item and the start of the next item in the array are incremental, and return true or false let arr = [{ start: 1, end: 3 }, { start: 1, end: 3 }, { start: 4, end: 5 }] function isTure(arr) { let status = true arr.reduce((pro, next) => { if (pro.end >= next.start) { status = false return false } return next }) return status } console.log(isTure(arr))
Here we use the return value of reduce to return the current item every time, so that the two parameters are always 1, 2 | 2, 3 | 3, 4 and so on
map and filter tomorrow