Preface:

This is my sixth day on the job. In the first two days, I solved a left bug of front-end page, which was used in the company’s projectelement-uithetableTable to show which department permissions employees have, the table is similar to the following figure:

Here’s the problem: when we add a new department under the page table, the page table gets messed up.
At first I thought there was a problem with the table merge part of the code, but it turned out to be the page rendering that wasn’t properly grouped.
To solve

I went to Google for relevant solutions, and I used the groupByWith method in the project:

function groupByWith(xs, key) {
      return xs.reduce(function (rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
 }
Copy the code

At first I didn’t understand this method, the parameter name is really confusing to me, but also a little spooky.

Note: THIS article is based on the groupByWith method I found on Google to explain, I will not bother to change its parameter name. However, in real projects, it is not recommended to use such silly parameter names

In addition, MY impression of Reduce is not very deep, so I went to the official website to review reduce, and then write down here for a record.

Follow the instructions on the reduce website to learn more about reduce

Introduction to the

The prototype chain of reduce is array.peototype.reduce (), from which we know that reduce is an Array method

The official explanation: The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

grammar

Arr. Reduce (Callback (Accumulator, currentValue [,index[, array]]) [, initialValue]) The values enclosed in brackets are optional.]

Parameters that

1. Callback functions

  • Accumulator: Is an accumulator
  • CurrentValue: indicates the currentValue
  • Index (Optional) : indicates the current index
  • Array (Optional) : source array

2. InitialValue (optional) : initialValue

The return value

The cumulative processing result of the function

describe

Reduce performs the callback function for each element in the array in turn, excluding elements in the array that were deleted or never assigned

There are two cases when the callback function is first executed:

  • InitialValue — > Accumulator is initialValue and currentValue is the value with index 0 in the array
  • — > Accumulator is an array with an index of 0 and currentValue is an array with an index of 1
Pay attention to
  1. If no initialValue is provided, Reduce executes the callback method starting at index 1, skipping the first index. If an initialValue is provided, it is executed from where the index is 0.
  2. If the array is empty and no initialValue is provided, TypeError is raised
  3. If the array has only one element and no initialValue is provided, or if initialValue is provided but the array is empty, this unique value will be returned and the callback will not be executed.
  4. It is usually safer to provide initial values.

Website case

Classify objects by attribute

Part of the project code display and analysis

Sorting Object arrays by attributes is one of the most common uses of reduce.

In fact, the groupByWith method I used in the project is logically no different from the case on reduce official website, but the code has become more concise and compact.

Reduce is already known. In the code used in my project, it provides reduce with an initial value {}, and we already know the logic for providing an initial value as follows:

  • accumulator = initialValue
  • currentValue = array[0]

That is, because an initial value is provided, reduce executes the callback method starting at index 0

The third line of groupByWith is the most difficult to understand. Because it is written very compact, it feels a little confused at first glance. But in fact, with a piece of JSON data, we split it up and take a closer look.

var peopleArray = [
  {
    name: 'Joe'.department: 'A'
  },
  {
    name: 'bill'.department: 'A'
  },
  {
    name: 'Joe'.department: 'B'}];function groupByWith(xs, key) {
      return xs.reduce(function (rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
      }, {});
 }
var groupedPeople = groupByWith(peopleArray, 'name');

console.log(groupedPeople);
//  { 
/ / zhang SAN: [{name: "zhang", the department: department of "A"}, {name: "zhang", the department: department of "B"}].
[{name: "id ", department:" id "}]
/ /}

Copy the code
thegroupByWithThe third line of this method breaks down to explain:
  1. (rv [ x[ key ] ] = rv[ x [ key ] ] || [])
  • x[ key ]: x is the currentValue, and for the first loop, x is equal to{name: “zhang SAN “, department:” department A”}.keyIt’s what comes in from the outsidename“, then the code finally comes outZhang SANThis string
  • rv [ x[ key ] ]: For the first loop, we know that the accumulator = the initial value, so we’re actually adding a property to the accumulator,keyZhang SANThat is, the property name is dynamically computed and then added to the object.
  • = rv[ x [ key ] ] || [] : rv[ x [ key ]The result is to take the value of an attribute in the accumulator object, i.eRv, so this is rvkeyZhang SANvalue. The short answer is: if there isIf Jack 3 **, he gets it firstZhang SANValue of (array value), and then into this valuepushStuff, if not declare an empty array.
  1. .push(x)
  • Using the array obtained in the previous step as a base, call.push to add new items to it.

If only the shadow of Perso Do not perso –