Retrieve unique child objects from an array I'm using TypeScript but this example is in plain JavaScript. I have a class rank with a child-class master. I need an ordered collection of unique masters. Here's what I have but it seems a little "kak":

function getMasters() {
    var gms = [];
    _.each(this.ranks, (r) =&gt; {
        if (gms[r.master.id])
            return;
        gms[r.master.id] = new ExtendedRank(r.master.id r.master.code, r.master.name);
    });

    return _.without(gms, undefined).sort(this.sort);
}


This is the sort function (which I'm relatively happy with):

function sort(l: ExtendedRank, r: ExtendedRank) {
    return l.sortString.localeCompare(r.sortString);
}
Here's a more functional solution, which based on your example is what you're looking for.  It relies on the uniqueness of object keys.  Note it's untested, but the idea should work:

function getMasters() {
  var extended = r =&gt; new ExtendedRank(r.master.id r.master.code, r.master.name),
  return Object.values(
    this.ranks.reduce((m,r) =&gt; Object.assign(m, {[r.master.id]: extended(r)}), {});
  ).sort(this.sort);
}


If you're looking to go even further in this direction, I recommend checking out ramda as a better, more functional alternative to underscore.