0

I have 2 arrays with objects.

const a = [
 {
  name: 'John'
 },
 {
  name: 'Adam'
 }
]

const b = [
 {
  name: 'Adam'
 }
]

I want to get the object is not the same in the array and also get the object that is same in arrays as well.

const same = [
 {
  name: 'Adam'
 }
]

const not_same = [
 {
  name: 'John'
 }
]

Using lodash library is it possible?

2
  • 1
    Have you tried anything? Commented Aug 4, 2017 at 6:47
  • try something on your own, and then come back with the question. HINT: lodash.com/docs/4.17.4#find Commented Aug 4, 2017 at 6:52

2 Answers 2

2

You can use intersectionBy and xorBy as follows:

const a = [{
    name: 'John'
  },
  {
    name: 'Adam'
  }
];

const b = [{
  name: 'Adam'
}];

console.log(_.intersectionBy(a, b, 'name')); // values present in both arrays
console.log(_.xorBy(a, b, 'name')); // values present in only one of the arrays
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

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

Comments

0

You can use _.partition() to get two arrays according to a certain criteria:

const a = [{
    name: 'John'
  },
  {
    name: 'Adam'
  }
];

const b = [{
  name: 'Adam'
}];

const bMap = _.keyBy(b, 'name'); // create a map of names in b
const [same, not_same] = _.partition(a, ({ name }) => name in bMap); // partition according to bMap and destructure into 2 arrays

console.log('same: ', same);

console.log('not_same: ', not_same);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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.