0

I have an array with objects and each object has a unique ID. I need to separate these objects according to their ID's and create new arrays containing objects with only the same ID.

This is what I have so 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 WITH MATCHING ID'S

      }

    })

  })

}

separateObjectsInArray(fullArray);

As you can see I first mapped out the array of objects then created an array with the ids, then took out any duplicates (uniqueIdArr) Afterwards I am mapping the fullArray again and comparing the IDs of each objects to the ID's uniqueIdArr. I'm stuck on how to tell it to create an array for each ID and push matching objects.

let finalArray1 = [{
  name: 'John',
  id: 1
}, {
  name: 'Lucy',
  id: 1
}];

let finalArray2 = [{
  name: 'Tyler',
  id: 2
}];

OR even one array with the arrays is fine too!

let finalArray = [[{name: 'Tyler', id: 2 }], [{ name: 'John', id: 1},{ 
name: 'Lucy', id: 1 }]];
2
  • sortedArr = finalArray.sort(function(a,b) { return b.id-a.id}); Commented Jul 28, 2017 at 20:03
  • 2
    I have an array with objects and each object has a unique ID, followed by create new arrays containing objects with only the same ID - one of these things is not like the other :) Commented Jul 28, 2017 at 20:10

2 Answers 2

5

You can use reduce to build a Map keyed by id, and finally get the values out of that array to form a 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; }

Sign up to request clarification or add additional context in comments.

Comments

0

If you can use lodash, here is another solution for you.

let fullArray = [
    { name: 'John', id: 1 },
    { name: 'Sarah', id: 2 },
    { name: 'Lucy', id: 1 },
    { name: 'Tyler', id: 2 }];

const grouped = _.groupBy(fullArray, "id");
console.log(Object.keys(grouped).map((key) => grouped[key]));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.