1

Noob javascript enthusiast here.

I'm trying to understand the various higher-order functions of javascript, and am particularly curious with the possibilities of .map() on an array of objects.

Suppose you have the following:

selectedId = ['u1', 'u2']
data = [
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'},
{id: 'u3', color: 'yellow', age: '15'}
]

How would you go about creating a new array that only contains the object of u1 and u2? I.e:

selectedData = [
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'},
]
1
  • from which array depends the order of the result? have you tried anything? what does not work? Commented Apr 18, 2020 at 15:25

2 Answers 2

3

You would have to Array#map over your selectedId array, then find corresponding object inside data array using Array#find.

const selectedId = ['u1', 'u2'];

const data = [
  {id: 'u1', color: 'red', age: '24'},
  {id: 'u2', color: 'blue', age: '18'},
  {id: 'u3', color: 'yellow', age: '15'}
];

const res = selectedId.map((id) => data.find((o) => o.id === id));

console.log(res);

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

Comments

1

If I understand it correctly, You can use array filter like

data.filter(el => selectedId.includes(el.id));

would give

[
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'}
]

Or alternatively

selectedId.map((id) => data.find((el) => el.id === id));

would give

[
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'}
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.