1

请解释代码并详细说明代码背后运行的内容。

我对 if 部分感到困惑if(! acc[key])。这是否意味着如果键不在 acc 中并使用值数组设置键并跳出 if 语句并将 obj 推送到 acc 键值中?

如果键在 acc 中,则跳过 if 语句并使用另一个内存acc[key]并设置 acc 中的键并使用 obj 设置值。

我的解释正确吗?

var people = [{
    name: 'Alice',
    age: 21
  },
  {
    name: 'Max',
    age: 20
  },
  {
    name: 'Jane',
    age: 20
  }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function(acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];

    }
   acc[key].push(obj)
    return acc;

  }, {});
}
var groupedPeople = groupBy(people, 'age')
console.log(JSON.stringify(groupedPeople))
4

1 回答 1

1

if (!acc[key]) {...}只是检查您是否已经在累加器中为该键捕获了任何数据。如果那里还没有任何内容,则可以在其中放置一个空数组acc[key] = [];,以便在下一步中将数据推送到其中。

您的代码中的错误是您还包括了pushif 子句;这意味着您只会获得给定键的每个值的第一个对象。相反,您需要该键的每个值的所有对象。

这是一个修复,代码中的一些注释解释了它在每个步骤中所做的事情:

var people = [{
    name: 'Alice',
    age: 21
  },
  {
    name: 'Max',
    age: 20
  },
  {
    name: 'Jane',
    age: 20
  }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function(acc, obj) {
    // stepping through each object in the array:
    var key = obj[property]; // "key" is the value of the given property
                             // for this object
    if (!acc[key]) {         // if the accumulator doesn't already have
                             // data for that key,
      acc[key] = [];         // put an empty array there, so we can add
                             // data to it
    }
    // this next line was moved out of the if clause above it, because
    // you always want it to happen:
    acc[key].push(obj)       // push this object onto the accumulator 
                             // at that key
    return acc;              
  }, {});
}
var groupedPeople = groupBy(people, 'age')
console.log(JSON.stringify(groupedPeople))

于 2019-03-21T02:55:01.000 回答