I have 2 arrays
a = [2,3,1,4]
b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
How do I get b
sorted based on a
? My desir
Here's an alternative construction using Ramda that might be a bit more succinct, and the functions are pretty easy to repurpose for other things.
const {indexBy, prop, map, flip} = R
const a = [2,3,1,4]
const b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
const toIndexById = indexBy(prop('id'))
const findIndexIn = flip(prop)
const c = map(findIndexIn(toIndexById(b)), a)
console.log(c)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
This solution uses Array#sort with a helper object c
for the indices.
{
"1": 2,
"2": 0,
"3": 1,
"4": 3
}
var a = [2, 3, 1, 4],
b = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
c = a.reduce(function (r, a, i) {
r[a] = i;
return r;
}, {});
b.sort(function (x, y) {
return c[x.id] - c[y.id];
});
document.write('<pre>' + JSON.stringify(b, 0, 4) + '</pre>');
For greater objects, I suggest to use Sorting with map.
Plain javascript, using some methods of the Array
(ES2015
standard)
var a = [2,3,1,4];
var b = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
var c = [];
a.forEach(el => c.push(b.find(e => e.id == el)));
document.write(JSON.stringify(c, 0, 2));
Or may be simpler
b.sort(function(obj1,obj2){
return a.indexOf(obj1.id) > a.indexOf(obj2.id)
});