How to arrange an array with objects based on another array?
Solution 1:
Disclaimer: In the examples, I've remove properties not relevant to the question, and also renamed taskID
to tID
for brevity.
You can use Array.prototype.reduce
to achieve the desired result:
let arr = [{tID: 1},{tID: 5},{tID: 8}];
let sArr = [8, 1, 5];
const result = sArr.reduce((a,v) => a.concat(arr.find(({tID})=>tID===v)), []);
console.log(result);
You can also use Array.prototype.sort
:
let arr = [{tID: 1},{tID: 5},{tID: 8}];
let sArr = [8, 1, 5];
const result = arr.sort(
({tID: aID}, {tID: bID}) => sArr.indexOf(aID) - sArr.indexOf(bID));
console.log(result);
Array.prototype.map
will also do the job:
let arr = [{tID: 1},{tID: 5},{tID: 8}];
let sArr = [8, 1, 5];
const result = sArr.map(i => arr.find(({tID}) => tID === i));
console.log(result);
map
and reduce
will probably perform faster than sort
because each iteration only requires a single lookup (find
) in the toSortArray
, as opposed to sort
, which requires two lookups (indexOf
).