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


i have 2 arrays:

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

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

i want two ordered publicid according one should be

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

is there built in method in nodejs this?

i've got working not efficient. have method can move element 1 index movefromto(oldindex, newindex 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 use r=-1 things move - although works - doesn't seem best of ideas.

any ideas appreciated.

many thanks.

you can sort() , indexof()

var 1 = ['da22', 'ye66', '17hy'];  var 2 = [{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 create object one , sort object.

var 1 = ['da22', 'ye66', '17hy'];  var 2 = [{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