JavaScript Group and array of objects with an array of keys

I have this snippet of code, am currently using typescript but it doesn’t matter right now. I just need a working code.

const ids = [3, 5];

const data = [
  {
    user: 'faith',
    nums: [1, 2, 3, 4]
  },
  {
    user: 'ngozi',
    nums: [4,7,2,45,6]
  },
  {
    user: 'chioma',
    nums: [2,3,5,7]
  },
  {
    user: 'peter',
    nums: [1,5,7,9]
  },
  {
    user: 'goodnews',
    nums: [2,4,8,0]
  },
  {
    user: 'peter',
    nums: [1,3,5,7]
  }
];

looking for a way to group data using a filter in nums with respect to ids. the expected result is

const result = {
  3: [
    {
      user: 'faith',
      nums: [1, 2, 3, 4]
    },
    {
      user: 'chioma',
      nums: [2,3,5,7]
    },
    {
      user: 'peter',
      nums: [1,3,5,7]
    }
  ],
  5: [
    {
      user: 'chioma',
      nums: [2,3,5,7]
    },
    {
      user: 'peter',
      nums: [1,5,7,9]
    },
    {
      user: 'peter',
      nums: [1,3,5,7]
    }
  ]
}

lodash option is also allowed

Answer

const ids = [3, 5];

const data = [{
    user: 'faith',
    nums: [1, 2, 3, 4]
  },
  {
    user: 'ngozi',
    nums: [4, 7, 2, 45, 6]
  },
  {
    user: 'chioma',
    nums: [2, 3, 5, 7]
  },
  {
    user: 'peter',
    nums: [1, 5, 7, 9]
  },
  {
    user: 'goodnews',
    nums: [2, 4, 8, 0]
  },
  {
    user: 'peter',
    nums: [1, 3, 5, 7]
  }
];

let result = {};
ids.map((num) => {
  let filteredRes = data.filter((x) => {
    if (x.nums.indexOf(num) > -1) {
      return x
    }
  });
  result[num] = filteredRes
});

console.log(result);

You can try map over the ids and then filter the data array to obtain objects with that Id.

Leave a Reply

Your email address will not be published. Required fields are marked *