编写一个函数“groupBy(array, callback)"; [英] Write a function "groupBy(array, callback)"

查看:12
本文介绍了编写一个函数“groupBy(array, callback)";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JavaScript 任务,我必须实现一个函数groupBy",当给定一组对象和一个函数时,返回一个对象,其中输入对象由对每个对象调用 fn 的结果键控.

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.

本质上,我必须编写一个函数groupBy(array, callback)",返回一个返回以下内容的对象.

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

例如:

  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.

推荐答案

纯JS解决方案:

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

function groupBy(array, callback) {
  return array.reduce(function(store, item) {
    var key = callback(item);
    var value = store[key] || [];
    store[key] = value.concat([item]);
    return store;
  }, {})
}

console.log('example 1: ', groupBy(list, function(i) { return i.id; }));
console.log('example 2: ', groupBy(list, function(i) { return i.name.length; }));

这篇关于编写一个函数“groupBy(array, callback)";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆