skip to Main Content

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)

3

Answers


  1. 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});
        }
    }
    
    Login or Signup to reply.
  2. A more concise and efficient version would first map over the foods to get an array of names, and then create a new array by filtering out the fruits objects whose name value is not included in the foodNames array.

    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"}];
    
    const foodNames = food.map(f => f.food_name);
    const notInFood = fruits.filter(f => !foodNames.includes(f.name));
    
    console.log(notInFood);
    Login or Signup to reply.
  3. const newArr = [];
    for (let i = 0; i < fruits.length; i++) {
      const findElement = food.find((obj) => obj.food_name === 
        fruits[i].name);
       if (!findElement) newArr.push(fruits[i]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search