Home > Mobile >  Rearrange object in an array JavaScript
Rearrange object in an array JavaScript

Time:04-26

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
},
]

CodePudding user response:

  • 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);

CodePudding user response:

You can simply sort array by priority.

yourArray.sort((a, b) => a.Priority>b.Priority?1:-1);

CodePudding user response:

You could take an object for the indices and create a new array and filter it.

const
    order = [1, 2, 3],
    data = [{ 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 }],
    indices = Object.fromEntries(order.map((k, v) => [k, v])),
    result = data
        .reduce((r, o) => {
            r[indices[o.Priority]] = o;
            indices[o.Priority]  = order.length;
            return r;
        }, [])
        .filter(Boolean);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A different approach.

const
    order = [1, 2, 3],
    data = [{ 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 }],
    temp = data.reduce((r, o) => {
        (r[o.Priority] ??= []).push(o);
        return r;
    }, {}),
    result = [];

let i = 0, go = true;

while (go) {
    go = false;
    for (const k of order) {
        if (!temp[k].length) break;
        result.push(temp[k].shift());
        go ||= temp[k].length;
    }
}


console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

This is what I came up with, it's rather crude but works fine.

const testList = [
  { 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 },
];

function prioritySort(arr, priority) {
  arr = arr.slice(); //copies the array

  let result = [];
  let p = priority[0];
  let c = 0;

  while (arr.length > 0 || c > 10000) {
    c  ;

    for (let curr in arr) {
      if (arr[curr].Priority == p) {
        result.push(arr[curr]);

        arr.splice(curr, 1);

        break;
      }
    }

    if (c == priority.length) {
      p = priority[0];
      c = 0;
    } else {
      p = priority[c];
    }
  }

  return result;
}

console.log(prioritySort(testList, [1, 2, 3]));

  • Related