Best Coffe Best Coffe - 5 months ago 11
Javascript Question

Javascript array containts element

I'm new in javascript and i have a question.
i have an array of element, i want to test if the array containts a specified element then update it if not add a new element.

for (var i = 0; i < datasourcedatas.length; i++) {
alert(item.id+" itemid "+ datasourcedatas[i].id);

if(item.id==datasourcedatas[i].id){
alert(item.id+" itemid "+ datasourcedatas[i].id+" boucle");
datasourcedatas[i].produitqan=qan;
item.produitqan=qan;
break;
}
else {
cartDataSource.add(item);
}
}

Answer

I assume the question is asking why the item gets added repeatedly.

The reason is that you're adding it on every iteration of the loop if that iteration's entry doesn't match.

Instead, you need to determine whether the entry is in the array using the loop, then only add it if not afterward, when done looping.

var found = false;
for (var i = 0; i < datasourcedatas.length; i++) {
    if (item.id == datasourcedatas[i].id) {
        found = true;
        datasourcedatas[i].produitqan = qan;
        item.produitqan = qan;
        break;
    }
}
if (!found) {
    cartDataSource.add(item);
}

Technically, you don't need the found variable, you could use i:

// I don't like or suggest this, just pointing it out
for (var i = 0; i < datasourcedatas.length; i++) {
    if (item.id == datasourcedatas[i].id) {
        datasourcedatas[i].produitqan = qan;
        item.produitqan = qan;
        break;
    }
}
if (i >= datasourcedatas.length) {
    cartDataSource.add(item);
}

Note that ES2015 added Array#find, which is useful for this and can be shimmed/polyfilled:

var found = datasourcedatas.find(function(entry) {
    return item.id == entry.id;
});
if (found) {
    found.produitqan = qan;
    item.produitqan = qan;
} else {
    cartDataSource.add(item);
}