I am completely baffled by the error that I am running into. I have been trying for hours to find a way around this, I wonder if anyone has seen anything like this before or knows what's going on.
Basically what is happening is that I have 2 arrays that are populated with objects. I want to look at them and check if all of the elements of the 2nd array (compare in the compareArrays() function) exist in the 1st array (myArray). If there are multiple instances of the same object in the compare array there should be the same number in the first.
I am using Angular with Typescript. Here is my code:
/*
* I get todaysItems a little higher in the constructor from a different service. It looks
* like this:
* {
* day: "Monday",
* price: 5.00,
* items_name: "1/4 Pounder with Cheese and Chips",
* items: [
* {name: "1/4 Pounder with Cheese", price: 4.50},
* {name: "Small Chips", price: 2.50}
* ],
* ad_hoc_price: 7
* }
*/
private todaysItems: Item[] = [];
compareArrays (myArray: Item[], compare: Item[]) {
var self = this;
if (compare.every(function(val) {
var index = self.arrayObjectIndexOf(myArray, val.name, "name");
if (index !== -1) {
myArray.splice(index, 1);
return true;
} else {
return false;
}
})) {
return true;
} else {
return false;
}
}
arrayObjectIndexOf(myArray, searchTerm, property) {
for(var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i][property] === searchTerm) {
return i;
}
}
return -1;
}
/*
* The cart has a property items_in_cart which is working fine, I can add elements to it
* and remove them with no issue.
*/
addItem (item: Item, totalPrice: number, cart: Cart) {
totalPrice += item.price;
cart.items_in_cart.push(item);
return {
newPrice: totalPrice,
newCart: cart
}
}
Ok, so the addItem() function works fine, just like expected. But the bizarre thing is that when I change it so it looks like
addItem (item: Item, totalPrice: number, cart: Cart) {
totalPrice += item.price;
cart.items_in_cart.push(item);
console.log(this.compareArrays(cart.items_in_cart, this.todaysItems));
return {
newPrice: totalPrice,
newCart: cart
}
}
Just adding that little console.log() which calls my compareArrays() function kicks all of the elements of this.todaysItems out of cart.items_in_cart. It is super bizarre and I have no idea what is happening.
Any ideas?
compareArraysfunction that is evil. That is why. Specifically, it does not do what it claims. It is like "If we find a match, then we start destroying stuff!". If a function does that it should not be namedcompareArrays.myArraythat are todays special items(price discounted). Do you want achieve this