Ruslan
Ruslan

Reputation: 134

Can't cleanly break out of the for loop in javascript

Got this simple example:

const arr = [
  {name: 'first', amount: 2},
  {name: 'second', amount: 1},
  {name: 'third', amount: 1}
]
const obj = {name: 'second', amount: 3}

for (let i = 0; i < arr.length; i++) {
  if (arr[i].name === obj.name) {
    arr[i].amount += obj.amount;
    break;
  } else {
    arr.push(obj)
  }
}

I want to execute the ordinary for loop and the desired result is that if there's an object with the same name as in the array, then just add up the amount, else I want obj to be pushed to the list. But in fact both events happen. How to make so when I break out from if statement the else statement won't run?

Upvotes: 1

Views: 156

Answers (3)

brk
brk

Reputation: 50291

You can use array findIndex and check if there exist an object where name is same as that of object. findIndex return -1 is no result is found. In that case push the obj in the array , else update the amount value

const arr = [{
    name: 'first',
    amount: 2
  },
  {
    name: 'second',
    amount: 1
  },
  {
    name: 'third',
    amount: 1
  }
]
const obj = {
  name: 'second',
  amount: 3
}


let ifKeyExist = arr.findIndex((item) => {
  return item.name === obj.name
})

if (ifKeyExist === -1) {
  arr.push(obj)
} else {
  arr[ifKeyExist].amount += obj.amount
}
console.log(arr)

Upvotes: 0

str
str

Reputation: 44979

An arguably more readable way to solve this is using Array#find as follows:

const arr = [
  {name: 'first', amount: 2},
  {name: 'second', amount: 1},
  {name: 'third', amount: 1}
];
const obj = {name: 'second', amount: 3};

const element = arr.find(el => el.name === obj.name);

if (element) {
  element.amount += obj.amount;
} else {
  arr.push(obj);
}

console.log(arr);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

You need another variable found and set it to true, if the data set is found. Then do not push the actual data set to the array.

Basically you neet to visit all elements and at the end decide if you add the object to the array.

With your code, you take at least one action, either update the actual data set end exit, which works only if the wanted name is in the first element, or you push an object to the array. This takes place until the wanted data set is found, or no more elements are available.

const arr = [{ name: 'first', amount: 2 }, { name: 'second', amount: 1 }, { name: 'third', amount: 1 }];
const obj = { name: 'second', amount: 3 };

var found = false;

for (let i = 0; i < arr.length; i++) {
    if (arr[i].name === obj.name) {
        arr[i].amount += obj.amount;
        found = true;
        break;
    }
}

if (!found) {
    arr.push(obj);
}

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions