Immediately faced golden nine silver ten again, and a good time to find a job, this several days with the company’s hr little sister chatted when you eat in the morning and ask about recent recruitment resume closed in, she said every day received resumes more than ever, (hurt, she won’t think that I also want to jump ship ~ ~ ~) and remembered before I find a job in the interview, it is the tears ~ ~

I remember interviewing for a company,

The interviewer asks: Have you heard of Reduce?

Me: That must listen to ah

Interviewer: So you use reduce to implement array de-duplication?

My heart is running wild ~~

As a result, there is no need to say more about this noodle, and come back to take a closer look at the use of reduce

grammar

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

parameter

The callback required. The function used to execute each array element.

  • Accumulator initial value, which is the cumulative value returned when the callback was last called
  • CurrentValue Indicates the current element
  • Index Indicates the index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1.
  • Array Array of calls to reduce() (optional)

InitialValue the initialValue passed to the function (optional)

usage

What can Reduce do in the first place? It is a new method in the ES5 array that can be used for summing, de-duplicating, composing, and so on

  • sum
[0, 1, 2, 3].reduce((accumulator, currentValue)=> { return accumulator + currentValue; }, 0); / / and is 6Copy the code
  • duplicate removal
Var arrData = [{id: 0, name: "xiao Ming"}, {id: 1, name: "zhang"}, {id: 2, name: "xiao li"}, {id: 3, name: "note"}, id: 1, the name: }, {id: 2, id: 2},]; var obj = {}; arrData = arrData.reduce((cur,next) => { if(! obj[next.id]){ obj[next.id] = true cur.push(next); } return cur; },[]) // Set the cur default type to array, and the initial value is null array console.log(arrData); // Prints the result of the array decrementCopy the code

A look heavy this writing method, too simple, using the object’s key value unique, ah, think of that time, my head is really funny

  • combination

This is a combination we often see used in source code in Redux

The source code

I often use this Reduce API in my work. I always wonder how it is implemented. So I think I can see if I can do it manually, simulating the source code

Array.prototype.reduce = function(callback,prev){array.prototype. reduce = function(callback,prev){ i<this.length; i++){ if(prev===undefined){ prev = callback(this[i],this[i+1],i+1,this) i++ }else{ prev = callback(prev,this[i],i,this) } } return prev }Copy the code

Hey, hey, it’s pretty simple