I have an array...
const order = [['sunglasses', 1], ['bags', 2]];
... an object...
const inventory = {
sunglasses: 1900,
pants: 1088,
bags: 1344
};
...and the following argument in the body of a function:
let inStock = order.every(item => inventory[item[0]] >= item[1]);
I know that the every() has been called on the array order and will return a Boolean based on the condition presented (in lay terms, if there are enough items in the inventory to fulfil the order it returns true, otherwise it returns false). Problem is, I can't wrap my head around how the every() method knows which items should be compared against and what exactly the indexes of [0] and [1] represent in this situation.
Simple explanation
Inventory is a lookup table, item[0] is the name of the item passed to every and item[1] is the number of items in the order
Every iteration of the order passes [itemname, number of items] to the function. itemname is used to look up the inventory and number of items are compared to number if inventory. All of them have to match to satisfy every
In the callback provided to every, the first argument is the item being iterated over, and the callback is called for every element in the array until one of the callbacks returns something falsey, or until the array is exhausted.
You could implement it yourself like this:
Array.prototype.myEvery = function(callback) {
for (const element of this) {
const result = callback(element);
if (!result) return false;
}
return true;
}
So here
.every(item => inventory[item[0]] >= item[1]);
item is one of the items of the array being iterated over - eg ['sunglasses', 1] or ['bags', 2]. Then the bracket notation extracts the value from the subarray, and it becomes something like
inventory['sunglasses'] >= 1
or
inventory['bags'] >= 2
with the result being returned. If all callbacks return a truthy value, the result of the .every call is true.