Rearrange object in an array JavaScript

Issue

I have PriorityArray as

[1, 2, 3]

and response json as

[ {
Id: 1,
Name:”aaa”,
Priority:1
},
{
Id: 2,
Name:”bbb”,
Priority:1
},
{
Id: 3,
Name:”ssss”,
Priority:2
},
{
Id: 4,
Name:”aaa”,
Priority:2
},
{
Id: 5,
Name:”dddd”,
Priority:1
},
{
Id: 6,
Name:”dddd”,
Priority:3
}]

I want to arrange all objects based on priority in rotation. Products should be arranged in an array like 1,2,3 then again append next products with priority 1,2,3

Expected output:

[ {
Id: 1,
Name:”aaa”,
Priority:1
},
{
Id: 3,
Name:”ssss”,
Priority:2
},
{
Id: 6,
Name:”dddd”,
Priority:3
}
{
Id: 2,
Name:”bbb”,
Priority:1
},
{
Id: 4,
Name:”aaa”,
Priority:2
},
{
Id: 5,
Name:”dddd”,
Priority:1
},
]

Solution

  • Group the response objects by their priority.

  • Then find the group that has highest no. of items in it.

  • And then loop over the grouped array until all elements have been added to the final array.

const priority = [1, 2, 3];
const res = [
  { Id: 1, Name: "aaa", Priority: 1 },
  { Id: 2, Name: "bbb", Priority: 1 },
  { Id: 3, Name: "ssss", Priority: 2 },
  { Id: 4, Name: "aaa", Priority: 2 },
  { Id: 5, Name: "dddd", Priority: 1 },
  { Id: 6, Name: "dddd", Priority: 3 },
];

const resGroupedByPriority = priority.map((p) =>
  res.filter((r) => r.Priority === p)
);

let index = 0;
let maxIndex = Math.max(...resGroupedByPriority.map((p) => p.length));
let ordered = [];

while (index < maxIndex) {
  resGroupedByPriority.forEach((p) => {
    if (p[index]) {
      ordered.push(p[index]);
    }
  });
  index += 1;
}
console.log(ordered);

Answered By – Som Shekhar Mukherjee

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.