user3760639
user3760639

Reputation: 73

Adding a new element or updating an existing element in an array

I have a bill array which contains items which the user chooses to place into it.

E.g., { item: 'Milk', cost: 1.99, quantity: 1 }

What I would like to do is update quantity to 2 if another milk is added to the basket and not add another milk item. This is the kind of code I have at the moment:

for (var i = 0; i < bill.length; i++) {
    if (newItem == bill[i].item) {
        bill[i].quantity++;
    }

    //IF IT CANNOT BE FOUND ADD NEW ITEM
    bill.push({
        item: newItem,
        cost: cost,
        quantity: 1});
}

Upvotes: 2

Views: 414

Answers (2)

David Conrad
David Conrad

Reputation: 16359

You can use the ECMAScript 6 Harmony array method findIndex():

function addItem(newItem, cost, quantity) {
    var index = bill.findIndex(function(element) {
        return element.item === newItem;
    });
    if (index >= 0) {
        bill[index].quantity += quantity;
    } else {
        bill.push({item: newItem, cost: cost, quantity: quantity});
    }
}

It will return the index of the element of the array that matches the predicate, or -1 if no such element is found. For example, the following code:

var bill = [{ item: 'Milk', cost: 1.99, quantity: 1 }];
addItem('Milk', 1.99, 1);
addItem('Bread', 1.00, 1);
console.log(bill);

produces the output:

[ { item: 'Milk', cost: 1.99, quantity: 2 }, { item: 'Bread', cost: 1, quantity: 1 } ]

The findIndex() method isn't very widely supported yet, but there is a findIndex() polyfill:

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

break out of the loop and set a flag if its found:

var found = false;
for(var i = 0; i < bill.length; i++){
    if(newItem == bill[i].item){
        bill[i].quantity++;
        found = true;
        break;
    }
}

if (!found) {
    bill.push({
        item: newItem,
        cost: cost,
        quantity: 1
    });
} 

Upvotes: 2

Related Questions