skip to Main Content

I want to compare between two arrays to get the id and name of the fruits that not exists in the food and deleted not equal to 1 then save the results in new array.

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

const food = [
{ id: '1', food_name: 'Bread', deleted: "0" }
  { id: '2', food_name: 'Orange', deleted: "0" },
  { id: '3', food_name: 'Cheese', deleted: "0" },
  { id: '4', food_name: 'Apple', deleted: "1" },
  { id: '5', food_name: 'Salt', deleted: "0" }
];

const dep_data = [];
var foodSet = new Set(food.map(item => item.id));
for (var j = 0; j < fruits.length; j++) {
  if (!foodSet.has(fruits[j].id) && food[j].deleted != '1') {
    dep_data.push({ id: fruits[j].id, name: fruits[j].name });
  }
}
console.log(dep_data);

For example here we have the Orange exist in the food array and deleted = 0, the results should store the id and name of fruits that doesn’t exist in food and deleted not equal to 1. (Apple, cherry).
Note: the comparison should be based on the ids and not on names.

2

Answers


  1. function compareArrays(arr1, arr2) {
      // Create a map to store names from arr2
      const nameMap = new Map();
      
      // Populate the name map with names from arr2
      for (const item of arr2) {
        nameMap.set(item.food_name, true);
      }
      
      // Compare names from arr1 with the name map
      for (const item of arr1) {
        if (nameMap.has(item.name)) {
          console.log(`${item.name} is present in both arrays`);
        } else {
          console.log(`${item.name} is not present in arr2`);
        }
      }
    }
    
    compareArrays(fruits, food);
    
    Login or Signup to reply.
  2. why so easy. is there nothing more difficult? lol

    const fruits = [
      { id: '1', name: 'Apple' },
      { id: '2', name: 'Orange' },
      { id: '3', name: 'Cherry' }
    ];
    const food = [
      { id: '1', food_name: 'Bread', deleted: "0" },
      { id: '2', food_name: 'Orange', deleted: "0" },
      { id: '3', food_name: 'Cheese', deleted: "0" },
      { id: '4', food_name: 'Apple', deleted: "1" },
      { id: '5', food_name: 'Salt', deleted: "0" }
    ];
    
    const dep_data = [];
    food.forEach((e,i) => {
      dep_data[i] = e
      if(e.deleted == 0) delete dep_data[i].deleted
      fruits.forEach((j,k) =>{
         if(j.id == e.id) dep_data[i] = Object.assign(dep_data[i], j)
      })
    })
    console.log(dep_data);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search