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

Got this simple example:

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?

JavaScript array : How to merge two arrays in JavaScript

JavaScript array : How to merge two arrays in JavaScript

In this post, We go over how to merge two arrays in JavaScript using the concat method and the spread syntax.

Array Concat() method

The concat method is used to merge two arrays. As a result, it returns a new array instead of modifying the existing array.

Let’s look at an example using the concat method. We have two arrays named fruits1 and fruits2. They both contain strings that correspond to a fruit.

const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = fruits1.concat(fruits2);

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]


Array Spread syntax

Now let’s look at an example using the spread syntax.


const fruits1 = ['apple', 'banana', 'grapes'];
const fruits2 = ['melons', 'watermelon'];

const combinedFruits = [...fruits1, ...fruits2];

console.log(combinedFruits); //[ 'apple', 'banana', 'grapes', 'melons', 'watermelon' ]

In this example, we created a new array and assigned it to the variable combinedFruits. We then took the two fruits array and used the spread them out in the array. We used the ... syntax to spread out the contents of the fruits array into the new array.

Thanks for reading !

Javascript Arrays | Beginners Javascript Tutorial

Javascript Arrays | Beginners Javascript Tutorial

This Javascript video covers Javascript arrays and looping arrays in Javascript. Arrays store lists of items of any type. You can iterate a Javascript array with loops, making it easy to run actions on all of the items in the array.

This Javascript video covers Javascript arrays and looping arrays in Javascript. Arrays store lists of items of any type. You can iterate a Javascript array with loops, making it easy to run actions on all of the items in the array.