-5

I have a array of ids and array of objects.

var ids = [4, 2, 5, 8]
var objs = [
            {"id": 2, "name": "a"}, 
            {"id": 4, "name": "b"}, 
            {"id": 8, "name": "c"}, 
            {"id": 5, "name": "d"}
        ]

I want to sort objs in order of values given in ids array.
so sorted objs should be

[
    {"id": 4, "name": "a"}, 
    {"id": 2, "name": "b"}, 
    {"id": 5, "name": "c"}, 
    {"id": 8, "name": "d"}
]
Alok
  • 7,734
  • 8
  • 55
  • 100

3 Answers3

1

You can map the ids array, example:

const ids = [4, 2, 5, 8]
const objs = [{
    "id": 2,
    "name": "a"
  },
  {
    "id": 4,
    "name": "b"
  },
  {
    "id": 8,
    "name": "c"
  },
  {
    "id": 5,
    "name": "d"
  }
]

const result = ids.map(id => objs.find((o) => o.id == id));
console.log(result);

To do this more efficiently, you can use:

const ids = [4, 2, 5, 8]
const objs = [{
    "id": 2,
    "name": "a"
  },
  {
    "id": 4,
    "name": "b"
  },
  {
    "id": 8,
    "name": "c"
  },
  {
    "id": 5,
    "name": "d"
  }
];

const map = objs.reduce((a, c) => (a[c.id] = c, a),{});

const result = ids.map(id => map[id]);
console.log(result);
Titus
  • 22,031
  • 1
  • 23
  • 33
1

For all items, you could map the wanted order by using a Map.

var ids = [4, 2, 5, 8],
    array = [{ id: 2, name: "a" }, { id: 4, name: "b" }, { id: 8, name: "c" }, { id: 5, name: "d" }],
    ordered = ids.map(Map.prototype.get, new Map(array.map(o => [o.id, o])));

console.log(ordered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can create order to sort:

let order = { 4: 1, 2: 2, 5: 3, 8: 4 };
objs.sort(function (a, b) {
  return order[a.id] - order[b.id];
});

An example:

var ids = [4, 2, 5, 8]
var objs = [
            {"id": 2, "name": "a"}, 
            {"id": 4, "name": "b"}, 
            {"id": 8, "name": "c"}, 
            {"id": 5, "name": "d"}
        ]

let order = { 4: 1, 2: 2, 5: 3, 8: 4 };


objs.sort(function (a, b) {
  return order[a.id] - order[b.id];
});

console.log(objs);
StepUp
  • 36,391
  • 15
  • 88
  • 148