javascript - Pushing objects with the same values to Array -


given have , array of objects:

let objects = [   {name: 'bob'},   {name: 'foo'},   {name: 'bar'},   {name: 'foo'},   {name: 'foo'} ] 

how can transform array one:

let objects = [   [     {name: 'bob'}   ],   [     {name: 'foo'},     {name: 'foo'},     {name: 'foo'}   ],   [     {name: 'bar'}   ] ] 

higher order functions

you use array .reduce() method iterate on array , put each object array in working object keyed off name property, afterwards use object.values() convert working object array of arrays:

let objects = [    {name: 'bob'},    {name: 'foo'},    {name: 'bar'},    {name: 'foo'},    {name: 'foo'}  ]    let result = object.values(objects.reduce((a,c) => {    if (!a[c.name]) a[c.name] = []    a[c.name].push(c)    return  }, {}))    console.log(result)


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 -