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)

>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});
    }
}

Leave a Reply