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

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 === { 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 arrays loops

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How To Loop Through An Array In JavaScript

In this tutorial, you'll be going to learn how to loop through an array in javascript. The easiest way to use for loop and forEach array method.

Learn Arrays And Array Methods in JavaScript

In JavaScript, an array is a data structure that contains list of elements which store multiple values in a single variable. The strength of JavaScript arrays lies in the array methods. Array methods are functions built-in to JavaScript that we can apply to our arrays — Each method has a unique function that performs a change or calculation to our array and saves us from writing common functions from scratch. In this video we are going to learn arrays and array methods like sort(), reverse(), join(), split(), pop(), push(), shift(), unshift(), toString(), delete array, etc.......

Javascript Clear Array: How to Empty Array in Javascript

To clear array in Javascript, Substituting an existing array with a new array.Setting an array length prop to 0.Splice the whole array.

Convert String To Array Using Javascript Split Method

In this tutorial, you’ll be going to learn how to convert string to array using javascript split method. The easiest approach to use javascript built-in method String.split(). JavaScript split string method return array of a substring after splitting a string based on the separator you provide. The separator might be a string, special character or […]

JavaScript 2D Array: Create Two Dimensional Array in JavaScript

To create a 2D array in JavaScript, we have to create an array of array. To declare a 2D array, use the same syntax as declaring a 1D array.