-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

1
  • 2
    what did you try so far? Commented Mar 23, 2020 at 7:44

2 Answers 2

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; }

Sign up to request clarification or add additional context in comments.

Comments

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);

6 Comments

I'd make it even simpler and use .map from sortedArray to entries in unSortedArray. No real need for reduce here.
You are right – I've updated the snippet (including flat)
If mapping one to many, you can just use .flatMap. But if it's just 1:1 mapping them a.map(x => b.find(y => <equality between x and y>)) suffices.
It all boils down to browser support :)
I don't think a browser that supports flat will not support flatMap or vice versa.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.