0

I have an array of objects:

const workouts = [
  {
    id: 1,
    name: "Bench Press",
    superset_id: 1,
  },
  {
    id: 2,
    name: "Squats",
    superset_id: 2,
  },
  {
    id: 3,
    name: "Shoulder Press",
    superset_id: 1,
  },
  {
    id: 4,
    name: "Leg Press",
    superset_id: 2,
  },
  ...
];

What I would like to do is filter the array for objects with a matching superset_id and return a new array that looks like this:

[
  [
    {
      id: 1,
      name: "Bench Press",
      superset_id: 1,
    },
    {
      id: 3,
      name: "Shoulder Press",
      superset_id: 1,
    },
  ],
  [
    {
      id: 2,
      name: "Squats",
      superset_id: 2,
    },
    {
      id: 4,
      name: "Leg Press",
      superset_id: 2,
    },
  ],
    ...
];

How can I achieve this?

pilchard
  • 12,414
  • 5
  • 11
  • 23
herbie
  • 335
  • 2
  • 14
  • this has been asked literally thousand times already: https://stackoverflow.com/search?q=%5Bjavascript%5D+groupby – gog Feb 18 '23 at 23:38
  • Does this answer your question? [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) – pilchard Feb 19 '23 at 00:46
  • or [Group Array of objects into 2D Array by the property of an object contained into an array](https://stackoverflow.com/questions/74703816/group-array-of-objects-into-2d-array-by-the-property-of-an-object-contained-into) or [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) ad infinitum – pilchard Feb 19 '23 at 00:47

3 Answers3

0

Use a combination of Math.max() and .map() to find the largest superset_id in the data, then filter the data for every superset_id. Like this:

const data = [{id:1,name:"Bench Press",superset_id:1},{id:2,name:"Squats",superset_id:2},{id:3,name:"Shoulder Press",superset_id:1},{id:4,name:"Leg Press",superset_id:2},];

const maxSuperset = Math.max(...data.map(el => el.superset_id));
const res = [];
for (let i = 1; i <= maxSuperset; i++) {
  res.push(data.filter(el => el.superset_id === i));
}
console.log(res)
Michael M.
  • 10,486
  • 9
  • 18
  • 34
0

You can use Array#reduce with an object to store the values for each id.

const workouts=[{id:1,name:"Bench Press",superset_id:1},{id:2,name:"Squats",superset_id:2},{id:3,name:"Shoulder Press",superset_id:1},{id:4,name:"Leg Press",superset_id:2},];
let res = Object.values(
  workouts.reduce((acc, curr) => {
    (acc[curr.superset_id] ??= []).push(curr);
    return acc;
  }, {})
);
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

As long as superset_id is incremental, this might be an idea.

const newArray = [];

array.forEach((elem) => {
  if(newArray[elem.superset_id - 1] === undefined) {
    newArray[elem.superset_id - 1] = [];
  }

  newArray[elem.superset_id - 1].push(elem);
});
DamiToma
  • 921
  • 3
  • 9
  • 27