patternjavascriptMinor
Writing a function to add or modify an existing object inside an array
Viewed 0 times
addarraywritingfunctionexistingobjectmodifyinside
Problem
I have an array of objects. Each object has two properties,
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
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
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.
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
});
}
};Solution
Why are you using an array to do the job of a map? Use the right data structures....
... instead, use a hashmap (associative array) of
... instead, use a hashmap (associative array) of
[id, quantity]. If id exists in hashmap, then increment up the value at hashmap[id].Context
StackExchange Code Review Q#43438, answer score: 9
Revisions (0)
No revisions yet.