-7
sortedArray = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]
unSortedArray = [{id: 8, text : 'abcd'}, {id: 4, text : 'ab'}, {id: 1, text : 'cd'}, {id: 2, text : 'def'}, {id: 3, text : 'abcd'}, {id: 5, text : 'abcd'}]

I want to sort unSortedArray based on items of sortedArray and want only object which has same id as in sortedArray

Result expected

[{id: 1, text : 'cd'}, {id: 2, text : 'def'}, {id: 3, text : 'abcd'}, {id: 4, text : 'abc'}]

I have tried similar suggestions based on similar questions. Adding link of such question here

Ankit Kumar
  • 3,663
  • 2
  • 26
  • 38

2 Answers2

0

Try this

let sortedArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
let unSortedArray = [
 { id: 8, text: "abcd" },
 { id: 4, text: "ab" },
 { id: 1, text: "cd" },
 { id: 2, text: "def" },
 { id: 3, text: "abcd" },
 { id: 5, text: "abcd" }
];

// Method 1 - Reduce
let sorted = sortedArray
 .map(itm => itm.id)
 .reduce((acc, id) => acc.concat(unSortedArray.filter(itm => itm.id === id)), []);

console.log(sorted);

// Method 2 - Map + flat
sorted = sortedArray
        .map(a => unSortedArray.filter(b => b.id === a.id))
        .flat();
;

console.log(sorted);


// Method 3 - flatMap
sorted = sortedArray
        .flatMap(a => unSortedArray.filter(b => b.id === a.id))
;

console.log(sorted);
Jakob E
  • 4,476
  • 1
  • 18
  • 21
0

You could get a hash table first and then map only wanted items.

var sortedArray = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
    unSortedArray = [{ id: 8, text : 'abcd' }, { id: 4, text : 'ab' }, { id: 1, text : 'cd' }, { id: 2, text : 'def' }, { id: 3, text : 'abcd' }, { id: 5, text : 'abcd' }],
    items = unSortedArray.reduce((r, o) => (r[o.id] = o, r), {}),
    result = sortedArray.map(({ id }) => items[id]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392