Home > database >  How to push elements to JS array according to a predetermined schema
How to push elements to JS array according to a predetermined schema

Time:12-01

I have an array of ids that determines the desired order of elements, which looks like this:

var desired_order = [0,4,2,1,3,...]

In my case it is much longer, so performance is to be considered.

I also have an array of objects with those ids, like this one:

var objects = [{name:"cat",id:0},{name:"dog",id:1},{name:"bird",id:2},{name:"elephant",id:3},
{name:"giraffe",id:4},...]

I need to create a new array var = objects_in_desired_order where these objects will be in the order determined by the desired_order array.

How to do that efficiently?

The only way I can think of is a double for loop where it goes over all possible ids in chronological order and pushes them where they belong. I would use this method if I wouldn't have such big arrays of data.

Thanks in advance!

CodePudding user response:

Turn your objects array into a map id => object:

let m = new Map(objects.map(o => [o.id, o]))

Then,

let objects_in_desired_order = desired_order.map(id => m.get(id))

BTW, stop using var.

CodePudding user response:

First make an object that maps values to ordering keys:

var orderMap = desired_order.reduce(function(map, value, index) {
  map[value] = index;
  return map;
}, {});

Now you can use that in a sort comparator:

objects.sort(function(o1, o2) {
  return orderMap[o1.id] - orderMap[o2.id];
});

The comparator will return a result based on the index of the id key in the original desired order array. The example above will sort the original objects array, so if you want to do the ordering in a new array you could objects.slice() it and make a new one to sort.

  • Related