Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare two equal value in two object

I want to compare these two arrays to get the id and name of the fruits that not exists in the food and save the results in new array.

For example here we have the Orange exist in the food array, the results should store the id and name of fruits that doesn’t exist in food. (Apple and Cherry).

const fruits = [{id: '1', name: 'Apple'},
{id: '2', name: 'Orange'},
{id: '3', name: 'Cherry'}];

const food=[{id: '1', creation_date: '2023-05-13 09:46:25', created_by: '1'},
{id: '1', food_name: 'Orange'},
{id: '2', food_name: 'Bread'},
{id: '3', food_name: 'Chees'},
{id: '4', food_name: 'Milk'},
{id: '5', food_name: 'Salt'}
]
//Code that I tried:
var res = {};
var dep_data = [];
for (var j = 0; j < fruits.length; j++) {
  for (var d = 0; d < food.length; d++) {
    if (parseInt(fruits[j].id) != parseInt(food[d])) {
      res["id"] = fruits[j].id;
      res["name"] = fruits[j].name;
      dep_data.push(res);
    }
  }
}
console.log(dep_data)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Set with complexity O(n + m) more efficient than nested loop which is O(n * m)

var foodSet = new Set(food.map(item => item.food_name));
for(var j=0; j < fruits.length; j++){
    if(!foodSet.has(fruits[j].name)){
        dep_data.push({id: fruits[j].id, name: fruits[j].name});
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading