userMod2 userMod2 - 3 months ago 11
Javascript Question

NodeJS/JS - Sorting based on another array + moving elements efficiently

I have 2 arrays:

var one = ['da22', 'ye66', '17hy']
and

var two = [{publicID: 'da22', score: '2'}, {publicID: '17hy', score: '2'}, {publicID: 'ye66', score: '2'}]


I want
two
to be ordered by
publicID
according to
one
so it should be

two = [{publicID: 'da22', score: '2'}, {publicID: 'ye66', score: '2'}, {publicID: '17hy', score: '2'}]


Is there a built in method in NodeJS to do this?

I've got it working however its not very efficient. I have a method than can move an element from one index to another
moveFromTo(oldIndex, newIndex
which I'm using with:

for (var r=0; r<one.length; r++) {
if (one[r] != two[r]['publicID']) {
two.moveFromTo(one.indexOf(two[r]['publicID']), r)
r=-1; continue;
}
}


But having to use that
r=-1
as things move - although works - doesn't seem like the best of ideas.

Any ideas would be appreciated.

Many Thanks.

Answer

You can do this with sort() and indexOf()

var one = ['da22', 'ye66', '17hy'];
var two = [{publicID: 'da22', score: '2'}, {publicID: '17hy', score: '2'}, {publicID: 'ye66', score: '2'}];

var result = two.sort(function(a, b) {
  return one.indexOf(a.publicID) - one.indexOf(b.publicID);
})

console.log(result)

You can also create object from one and sort by that object.

var one = ['da22', 'ye66', '17hy'];
var two = [{publicID: 'da22', score: '2'}, {publicID: '17hy', score: '2'}, {publicID: 'ye66', score: '2'}];

var o = one.reduce((r, e, i) => {return r[e]=i, r}, {});

var result = two.sort(function(a, b) {
  return o[a.publicID] - o[b.publicID];
})

console.log(result)

Comments