Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - Write a function "groupBy(array, callback)"

I have a JavaScript task where I have to implement a function "groupBy", which, when given an array of objects and a function, returns an object where the input objects are keyed by the result of calling the fn on each of them.

Essentially, I have to write a function, "groupBy(array, callback)", returns an object where the following is returned.

For example:

  var list = [{id: "102", name: "Alice"},
              {id: "205", name: "Bob", title: "Dr."},
              {id: "592", name: "Clyde", age: 32}];

  groupBy(list, function(i) { return i.id; });

Returns:

  {
    "102": [{id: "102", name: "Alice"}],
    "205": [{id: "205", name: "Bob", title: "Dr."}],
    "592": [{id: "592", name: "Clyde", age: 32}]
  }

Example 2:

  groupBy(list, function(i) { return i.name.length; });

Returns:

  {
    "3": [{id: "205", name: "Bob", title: "Dr."}],
    "5": [{id: "102", name: "Alice"},
          {id: "592", name: "Clyde", age: 32}]
  }

I'm still quite new to callback functions, and would like some tips/advice to simply get started. Even links to good tutorials would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a reduce() one-liner. Reduce allows you to loop through the array and append to a new object based on the logic of its callback. In this function a (for accumulated) is the object we're making and c (for current item) is each item in the loop taken one at a time.

It works especially concisely here because the function to make the object key is passed in:

var list = [{id: "102", name: "Alice"},
{id: "205", name: "Bob", title: "Dr."},
{id: "592", name: "Clyde", age: 32}];

function groupBy(list, Fn) {
    return list.reduce((a, c) => (a[Fn(c)] ? a[Fn(c)].push(c) : a[Fn(c)] = [c], a), {})
}

var t = groupBy(list, function(i) { return i.id; });
console.log(t)

var l = groupBy(list, function(i) { return i.name.length; });
console.log(l)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...