0

Is there a way with lodash, where in result I do not have an object that satisfies a particular condition. For example,

o1 = [
  {name: "a", id: 2, key: 33},
  ..,
]

o2 = [
 {name: "ab", id: 2, key: 133}
]

Is there a way with lodash where the resultant array only includes the object that does not have the ids already present in o2. For example, resultant object after comparing o1 and o2 must not have the object from o2 because id=2 already exists in o1.

Amanda
  • 2,013
  • 3
  • 24
  • 57

4 Answers4

3

You can use _.differenceBy() and use the id of the point of reference:

const o1 = [{id: 1, name: 'a'},{id: 2, name: 'b'},{id: 3, name: 'c'}]
const o2 = [{id: 1, name: 'b'}]

const result = _.differenceBy(o1, o2, 'id')

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You could do this without lodash by using .filter() and creating a Set. Firstly, you can create a set of all the ids in o2. Then, you can filter out any objects from o1 which have an id within the set. By using a set with .has() we are able to make our algorithm more efficient (than say using .includes() on an array).

See example below:

const o1 = [
  {name: "a", id: 2, key: 33},
  {name: "b", id: 3, key: 34},
  {name: "c", id: 4, key: 34}
]

const o2 = [
  {name: "d", id: 2, key: 134}
]

const o2_ids = new Set(o2.map(({id}) => id));
const result = o1.filter(({id}) => !o2_ids.has(id));
console.log(result); // includes objects with id's that appear in o1 but not in o2
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

Maybe _.differenceWith?

const o1 = [
  {id: 1, name: "a"},
  {id: 2, name: "b"},
  {id: 3, name: "c"},
]

const o2 = [
  {id: 1, name: "b"},
]

const diffed = _.differenceWith(o1, o2, (o1, o2) => o1.id === o2.id)

console.log(diffed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Derek Nguyen
  • 11,294
  • 1
  • 40
  • 64
0

<!DOCTYPE html>
<html>
<head>

</head>

<body>


<script>
var o1 = [
  {name: "a", id: 77, key: 55},
  {name: "a", id: 2, key: 33},
  {name: "a", id: 1, key: 55}
]

var o2 = [
 {name: "ab", id: 88, key: 133},
 {name: "ab", id: 2, key: 133},
 {name: "ab", id: 99, key: 133}
]
//sort first

o1.sort((a, b) => {
 return a.id-b.id;//sort by id
});

o2.sort((a, b) => {
 return a.id-b.id;//sort by id
});


//then compare one by one
function SearchX(OO1,OO2){
 var o1_compare_place=0;
 var o2_compare_place=0;


 while(OO2.length>o2_compare_place && OO1.length>o1_compare_place ){
  if(OO2[o2_compare_place].id<OO1[o1_compare_place].id){
   o2_compare_place+=1;
  }else if(OO2[o2_compare_place].id>OO1[o1_compare_place].id){
   o1_compare_place+=1;
  }else{
   return "Exist Same!";
  }
 }
 return "Different!";

}

document.body.innerHTML = SearchX(o1,o2)







</script>

</body>
</html>

Here you are

J CHEN
  • 494
  • 3
  • 9