最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Dec 10, 2019 at 15:14 EugenSunic 13.7k15 gold badges66 silver badges95 bronze badges asked Nov 12, 2017 at 5:26 kdubsskdubss 3333 silver badges12 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 5

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)

Solution with pure 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; }));

Heres a link to the code: http://rextester./KROB29161

function groupBy(list, callback) {
  // Declare a empty object
  var obj = {};

  // We then loop through the array
  list.forEach(function(item) {
    // We define the key of the object by calling the 
    // callback with the current item
    var key = callback(item);

    // If the field exists, add this item to it
    if (obj[key]) {
      obj[key] = obj[key].concat(item);
    } else {

      // If the field does not exist, create it and this value
      // as an array 
      obj[key] = [item];
    }
  });
  return obj;
}

You can use Lodash _.groupBy, it does exactly what you ask for. doc here.

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

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

Here's a link to working example: https://codepen.io/pablo-tavarez/pen/NwjrEZ?editors=0012

function groupBy(list, callback) {
  var output = {};
  var key
    , i = 0;

  // iterate over list of objects
  for ( ; i < list.length; i++ ) {
    // pass the current item to callback and get (current) key
    key = callback(list[i]);

    if (output[key]) {
      // handle duplicate keys without overriding -- (optionally make all key value Arrays)
      output[key] = [output[key]];
      output[key].push(list[i]);
    }
    else {
      output[key] = list[i];
    }
  }

  return output;
}

function groupBy(array, callback) {
  var object = {};

  for (var i = 0; i < array.length; i++) {
    var item = array[i];
    var key = callback(item);

    if (object.hasOwnProperty(key)) {
      object[key].push(item);
    } else {
      object[key] = [item];
    }
  }

  return object;
};

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

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

console.log(byId);

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

console.log(byNameLength);

Here is another approach using reduce:

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



 function groupBy(list, callback) {
   return list.reduce((acc, x) => {
     const key = callback(x);
     if (!acc[key]) {
       return {
         ...acc,
         [key]: [x]
       }
     }
     return {
       ...acc,
       [key]: [...acc[key], x]
     }

   }, {})
 }

// callback functions
 function nameLength(obj) {
   return obj.name.length;
 }

 function objectProperty(obj) {
   return obj.id
 }


 console.log('group by name length:', groupBy(list, nameLength));
 console.log('group by Id:', groupBy(list, objectProperty));

发布评论

评论列表(0)

  1. 暂无评论