Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

sorting an array of objects using callbacks

Hello! I'm having a hard time figuring out how to sort an array of objects based using callback functions

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

here is my code, my problem is I don't know how to check for values that are repeated in the key and group them together

function groupBy(arr, cb) {

  let newObject = {}
  let array2 = []

  for(var i = 0; i < arr.length; i++){
      if(cb(arr[i]) === cb(arr[i])){
        array2.push(arr[i])
          newObject[cb(arr[i])] = array2
      } else {

        let array = [];
        array.push(arr[i])
        newObject[cb(arr[i])] = array
      }
  }
    console.log(newObject)
    return newObject
}

here are the functions calls and expected results:

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}]
  }

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

Returns:

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

Please someone help!

2 Answers

I answered a similar question a while back, so I'll just copy my answer in here:

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

function groupBy(arr, callback) {
    //Object that will contain the key/val pairs
    var result = {};
    //Loop through the arr we passed in
    arr.forEach(obj => {
        //When we execute our callback function
        //We get back the value we want to groupBy
        var key = callback(obj);
        //If the key does NOT exist in the object,
        //then create it and set it equal an empty array
        if(!result.hasOwnProperty(key)) {
            result[key] = [];
        }
        //Push the object that corresponds to our key
        result[key].push(obj);
    });

    //We have our answer. 
    return result;
}

console.log(groupBy(list, function(obj) {
    return obj.id;
}));


/*
This prints:

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

Thanks so much, I spent 7 hours doing work arounds....