1

How would you either update inventory(based on name) or add if name not found.

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

For example, the following will update the inventory:

const fruit = {name: 'bananas', quantity: 1}
inventory = inventory.map(f => f.name===fruit.name ? fruit : f);

and this could be used to add to the inventory:

const fruit = {name: 'oranges', quantity: 2}
if (!inventory.find(f => f.name===fruit.name)) inventory.push(fruit)

but I'm looking for a solution which can do both and which preferably uses arrow functions rather than indexes - if possible.

Baz
  • 12,713
  • 38
  • 145
  • 268

2 Answers2

5

You can use findIndex:

var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

var fruit = {name: 'bananas', quantity: 1}

var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;

var fruit = {name: 'oranges', quantity: 2}

var idx = inventory.findIndex(f => f.name === fruit.name);
inventory[idx < 0 ? inventory.length : idx] = fruit;

console.log(inventory);

In case you want to merge two arrays of objects (instead of a single object to an array), then this approach would be quadratic. You should see JavaScript merging objects by id instead.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

If you don't have any reason to index the inventory with numbers, you should use an object as a dictionary. E.g.:

var inventory = {
    apples: { quantity: 2 },
    bananas: { quantity: 0 },
    cherries: { quantity: 5 }
};
let prop = "apples"
if (inventory.hasOwnProperty(prop))
  inventory[prop].quantity++;
else inventory[prop] = { quantity: 1 };

If your index does not use numbers nor strings, modern javascript has Map.

Should the array have to be as it is, there is also the possibility to lay an additional index structure over the inventory. Just be careful to wrap the structure to assure both get updated simultaneously.

Last but least, should you want an array and are sure the inventory is always small and search time will be negligible no matter how terrible the search function is, just iterate over the array (as has already been described in other answers).

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33