-1

I am building an app using ReactJS library and trying to figure out how to return a difference after comparing two arrays.

const a = [8,10,13,14];
const b = [{id: 8}, {id: 13}, {id: 14}];

and what I would like to get is [10].

What I have tried and didn't work was using map and filter together.

const newArray = b.map((itemB) => {
    return a.filter(
       itemA => itemB.id !== itemA,
    );
});

What is the simple way of returning this?

Thanks.

doobean
  • 1,929
  • 4
  • 19
  • 27
  • Show us what you tried. Numerous ways you can acheive this. SO isn't a free code writing service. The objective is to help you with your code – charlietfl Jul 24 '19 at 01:36
  • Yup, edited the question. Thanks for the feedback. – doobean Jul 24 '19 at 01:39
  • Possible duplicate of [How to get the difference between two arrays in Javascript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – minus.273 Jul 24 '19 at 08:37
  • @minus.273 Thanks for the comment, but I wanted to sort out when there are the object keys in an array. – doobean Jul 28 '19 at 21:22

3 Answers3

3

Why don't you just filter the unwanted id?

const a = [8, 10, 13, 14];
const b = [{ id: 8 }, { id: 13 }, { id: 14 }];

console.log(a.filter(num => !b.some(({ id }) => id === num)));
Brian Le
  • 2,646
  • 18
  • 28
2

As you have two array with different item-types, you could combine Array.filter() with Array.map() to get the difference:

const a = [8,10,13,14];
const b = [{id: 8}, {id: 13}, {id: 14}];

const normalized = b.map(({ id }) => id);
const diff = a.filter(value => !normalized.includes(value));

console.log(diff);

EDIT: I think @Brian Le's solution with .some() is more elegant (and probably more performant)!

exside
  • 3,736
  • 1
  • 12
  • 19
1

You can use lodash.

const diff = _.difference(a, b.map(({ id }) => id));
Philip Moy
  • 481
  • 3
  • 6