javascript - JS/Underscore: _.groupBy or _.uniq to get unique/grouped elements of field is existing -


a mongodb query gives me result array this:

var result = [   {     _id: 'grrq56zvtgpsajvcr',     title: 'element 1'     meta: {       groupid: '1'     }   },   {     _id: 'nqs7t5qzcjbyxe6yh',     title: 'element 2'     meta: {       groupid: '1'     }   },   {     _id: 'cbdqv6exzoyjqjlnp',     title: 'element 3'     meta: {       groupid: '2'     }   },   {     _id: 'v6exzoycbdqjqjlnp',     title: 'element 4'     meta: {       groupid: '2'     }   },   {     _id: 'qbqiegwsgyprfutzm',     title: 'element 5'     meta: {     }   },   {     _id: 'rfutzmqbqiegwsgyp',     title: 'element 6'     meta: {     }   } ] 

now need output each element without groupid , single element each identical groupid. (i cannot use distinct or aggregate directly on mongodb query, have work result)

so i'm thinking of using _.unique or _.groupby.

const resultgroupby = _.groupby(result, function(element) { return element.meta.groupid }) const resultunique = _.uniq(result, function(item, key, a) { return item.a }) // don't understand syntax :-( 

but both aren't working needed.

my result should be:

groupedresult.map((element) => {   console.log(element.title, kindofcounter) })  element 1, 2 // 2 elements group 1 element 3, 2 // 2 elements group 2 element 5, 1 // single element without group element 6, 1 // single element without group 

element 2 , element 4 removed, group 1 , group 2 should represented 1 element, although there 2 elements @ beginning.

i think _.uniq should want.

var result = [    {      _id: 'grrq56zvtgpsajvcr',      title: 'element 1',      meta: {        groupid: '1'      }    },    {      _id: 'nqs7t5qzcjbyxe6yh',      title: 'element 2',      meta: {        groupid: '1'      }    },    {      _id: 'cbdqv6exzoyjqjlnp',      title: 'element 3',      meta: {        groupid: '2'      }    },    {      _id: 'v6exzoycbdqjqjlnp',      title: 'element 4',      meta: {        groupid: '2'      }    },    {      _id: 'qbqiegwsgyprfutzm',      title: 'element 5',      meta: {      }    },    {      _id: 'rfutzmqbqiegwsgyp',      title: 'element 6',      meta: {      }    }  ];    var resultuniq = _.uniq(result, e => e.meta.groupid);  console.log(resultuniq.map(e => e.title));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

element 6 isn't included in result because has no groupid. change iteratee function returns default value when e.meta.groupid undefined.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -