WolfgangVonL WolfgangVonL - 4 months ago 11
Javascript Question

JAVASCRIPT reorder an array by group of consecutive values

I'm looking for a way to reorder an array by a set of consecutive fixed values. For example:

I have got an array of items:

items = [
{id: 1, name: "Test 1", group: 1},
{id: 2, name: "Test 2", group: 2},
{id: 3, name: "Test 3", group: 2},
{id: 4, name: "Test 4", group: 2},
{id: 5, name: "Test 5", group: 1},
{id: 6, name: "Test 6", group: 2},
{id: 7, name: "Test 7", group: 1},
{id: 8, name: "Test 8", group: 3},
{id: 9, name: "Test 9", group: 1},
{id: 10, name: "Test 10", group: 3}
];


I know also that I've got three groups:

groups = [
{id: 1, name: "Group 1"},
{id: 2, name: "Group 2"},
{id: 3, name: "Group 3"}
];


And what I want to do looks like to that:

new_array = [
{id: 1, name: "Test 1", group: 1},
{id: 2, name: "Test 2", group: 2},
{id: 8, name: "Test 8", group: 3},
{id: 5, name: "Test 5", group: 1},
{id: 3, name: "Test 3", group: 2},
{id: 10, name: "Test 10", group: 3}
{id: 7, name: "Test 7", group: 1},
{id: 4, name: "Test 4", group: 2},
{id: 9, name: "Test 9", group: 1},
{id: 6, name: "Test 6", group: 2},
];


I want to sort my array by "group" of 3 items following the order of group 1, 2, 3

Would you know a smart way of doing this ? I don't know where to start...

Answer

For reasonably small sets of data, you may want to go with a simple algorithm such as this one. Just keep in mind that findIndex() and splice() are rather costly methods, though.

var items = [
      {id: 1,  name: "Test 1",  group: 1},
      {id: 2,  name: "Test 2",  group: 2},
      {id: 3,  name: "Test 3",  group: 2},
      {id: 4,  name: "Test 4",  group: 2},
      {id: 5,  name: "Test 5",  group: 1},
      {id: 6,  name: "Test 6",  group: 2},
      {id: 7,  name: "Test 7",  group: 1},
      {id: 8,  name: "Test 8",  group: 3},
      {id: 9,  name: "Test 9",  group: 1},
      {id: 10, name: "Test 10", group: 3}
    ],
    groups = [
      {id: 1, name: "Group 1"},
      {id: 2, name: "Group 2"},
      {id: 3, name: "Group 3"}
    ];

var res = [], i, n;

for(n = 0; items.length; n = (n + 1) % groups.length) {
  if((i = items.findIndex(function(v) { return v.group == groups[n].id; })) != -1) {
    res.push(items.splice(i, 1));
  }
}

// displaying formatted output
console.log(JSON.stringify(res).split('}],').join('}],\n'));