Reputation: 49
I am trying to take a list grocery list and checks it against things you already have and puts it in a new list. I am learning how to iterate though lists and cannot figure out why I am getting the output that I am. I want the output to be a list of things that where not found in the list of things you already have. The output at the moment prints out what I need but multiple times. Not sure why. Thanks
let groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'];
let currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese','Bread','Water','Oil'];
let newList = [];
for (let i = 0; i < groceryList.length; i++) {
for (let j = 0; j < currentGrocery.length; j++){
if (groceryList[i] !== currentGrocery[j]){
newList.push(groceryList[i]);
}
}
}
console.log(newList);
Upvotes: 1
Views: 63
Reputation: 386624
You oculd filter the array.
const
groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'],
currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese', 'Bread', 'Water', 'Oil'],
newList = currentGrocery.filter(item => !groceryList.includes(item));
console.log(...newList);
Upvotes: 1
Reputation: 124
You push the item from your grocery list for every non-matching current grocery. What you want to do is to only push to the new list if there are no current grocery matches.
In a naive way, this could be achieved via
let found = false;
for (let i = 0; i < groceryList.length; i++) {
for (let j = 0; j < currentGrocery.length; j++){
if (groceryList[i] == currentGrocery[j]){
found = true;
break;
}
}
if (found) {
newList.push(groceryList[i]);
found = false;
}
}
A more readable approach makes use of the filter() and includes() functions:
let newlist = groceryList.filter(item => !currentGrocery.includes(item));
console.log(newlist);
Upvotes: 0
Reputation: 11
let groceryList = ['Bread', 'Cereal', 'Bagels', 'Water', 'Apple'];
let currentGrocery = ['Eggs', 'Lettuce', 'Milk', 'Cheese','Bread','Water','Oil'];
let newList = [];
currentGrocery.forEach(item =>{
if (!groceryList.includes(item)) newList.push(item);
})
console.log(newList);
Upvotes: 1