1

I'm new to JS and React and I'm a little stuck here. I've searched through SO but I'm having trouble finding a solution with an explanation that works.

Here are my arrays.

The first array is pretty simple.

[1, 3, 4,]

The second looks like this.

[
  {
    id: 1,
    title: Title 1,
   },
  {
    id: 2,
    title: Title 2,
   },
]

What I'd like to do is search the second array and if I can find an id that matches a value in the first array, add the object from the second array to third, new array.

I've tried a number of things and I'm sure there's a relatively easy way to do this with a forEach loop or lodash but I'm coming up blank.

Any help and explanations would be greatly appreciated.

Thanks,

1
  • 5
    I've tried a number of things Please post what you've tried. Commented Jul 22, 2018 at 4:32

1 Answer 1

6

Your second array is not valid. You have to wrap the string values with quotes.

You can use Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

and Array.prototype.includes()

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

Try the following way:

var arr1 = [1, 3, 4,];

var arr2 = [
  {
    id: 1,
    title: 'Title 1',
   },
  {
    id: 2,
    title: 'Title 2',
   },
];

var res = arr2.filter(i => arr1.includes(i.id));

console.log(res);

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

1 Comment

Perfect! Thank you for continuing my education!

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.