javascript - Separate objects in array and sort by id in new array for each id -


i have array objects , each object has unique id. need separate these objects according id's , create new arrays containing objects same id.

this have far..

let fullarray = [{   name: 'john',   id: 1 }, {   name: 'lucy',   id: 1 }, {   name: 'tyler',   id: 2 }];  function separateobjectsinarray(fullarray) {    let newarr = [];    fullarray.map((each) => {      newarr.push(each.id);    });    let uniqueidarr = [...new set(newarr)];    fullarray.map((eachobj) => {      uniquearr.map((uniqueid) => {        if (eachobj.id === uniqueid) {          //create new arrays matching id's        }      })    })  }  separateobjectsinarray(fullarray); 

as can see first mapped out array of objects created array ids, took out duplicates (uniqueidarr) afterwards mapping fullarray again , comparing ids of each objects id's uniqueidarr. i'm stuck on how tell create array each id , push matching objects.

let finalarray1 = [{   name: 'john',   id: 1 }, {   name: 'lucy',   id: 1 }];  let finalarray2 = [{   name: 'tyler',   id: 2 }]; 

or 1 array arrays fine too!

let finalarray = [[{name: 'tyler', id: 2 }], [{ name: 'john', id: 1},{  name: 'lucy', id: 1 }]]; 

you can use reduce build map keyed id, , values out of array form new array of arrays:

function group(arr, key) {      return [...arr.reduce( (acc, o) =>           acc.set(o[key], (acc.get(o[key]) || []).concat(o))      , new map).values()];  }    const fullarray = [{    name: 'john',    id: 1  }, {    name: 'lucy',    id: 1  }, {    name: 'tyler',    id: 2  }];    const result = group(fullarray, 'id');    console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -