I have an array of objects. Each object has two properties, id
and quantity
.
I wrote a function to add an object to the array. But the function must check if the object already exists within the array. If it does exist the function must increment the quantity
property. Otherwise it must add a new object.
Is there an idiomatic way to achieve the same result? I feel that looping over the array to compare the id of the object at index against the id passed as argument is not the right approach.
I am also suspicious of the found = false
temporary variable.
Finally, in Ruby we are encouraged to break down long methods into smaller ones. I am aware that JavaScript is not the same, but I feel that this could be further refactored.
addItem = function(id, items) { var found, i; found = false; i = 0; while (i < items.length) { if (id === items[i].id) { items[i].quantity++; found = true; break; } i++; } if (!found) { return items.push({ id: id, quantity: 1 }); } };