JavaScript ES5 allows for the choice between updating a value or pushing to an array

I've been attempting to add an object to an array of objects only if that specific object is not already in the array. If it is present, the object should be updated instead.

My requirement is to achieve this using es5.

Below is my current approach:

var database = require('../../database');
var autoincrementId = require('../../helpers/autoincrement-id');
var books = database.Books;

function Book(title, author, summary) {
  this.title = title;
  this.author = author;
  this.summary = summary;
}

Book.prototype.createBook = function () {
  var id = autoincrementId(id, database.Books); //autoincrement database id
  var copies = 1;
  var title = this.title.toLowerCase(), author = 
this.author.toLowerCase(), summary = this.summary.toLowerCase();
  if (!books.length) {
    books.push({id: id, title: title, author: author, summary: summary, copies: copies});
  } else {
     for(var book in books) {
      if(books[book].title === title) {
        books[book].copies += 1;
       break;
      }
      books.push({id: id, title: title, author: author, summary: summary, copies: copies});
    }
  }
};

However, when I execute the following:

var abook = new Book('J', 'k', 'l');
var bbook = new Book('M', 'N', 'o');
abook.createBook();
abook.createBook();
bbook.createBook();
bbook.createBook();

console.log(books);

I am getting the following result:

[ { id: 1, title: 'j', author: 'k', summary: 'l', copies: 2 },
  { id: 2, title: 'm', author: 'n', summary: 'o', copies: 2 },
  { id: 3, title: 'm', author: 'n', summary: 'o', copies: 1 } ]

Instead of:

[ { id: 1, title: 'j', author: 'k', summary: 'l', copies: 2 },
  { id: 2, title: 'm', author: 'n', summary: 'o', copies: 2 }]

I need help understanding what is causing this issue with the code. Why is it updating and inserting on the second attempt, and how can I resolve this?

Answer №1

When iterating through your for(var book in books) { loop, it is important to note that you are checking if the current book is equal to the new one. If they are not the same, the new book is added to the list. However, if the current book is actually the second one in the list, it will be added regardless, as the first book checked is not the new one. To prevent this, consider implementing a flag to ensure that no book was found during the iterative process:

var BookNotFound = true; // Set default value to indicate no book found
for(var book in books) {
    if(books[book].title === title) {
        books[book].copies += 1;
        BookNotFound = false; // Update the flag to indicate book was found
        break;
    }
}
// Once outside the loop :
if (BookNotFound)
    books.push({id: id, title: title, author: author, summary: summary, copies: copies});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a tree array in JavaScript from JSON data

I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result. [{ "code": "2", "name": "PENDING" },{ "code": "2.2", ...

Is it better to use Rollup for exporting individual components instead of lumping them all into one index.js

Currently, I am working on developing a custom component library using React and Rollup for bundling. The current setup bundles all components into two large files: dist ├ cjs │ └ index.js (1.7mb) └ esm └ index.js (1.7mb) I would like to ...

To effectively utilize the expect function in testing, should you use it over softAssertAll or find a way to explicitly display in the test results that the softAssertAll has successfully passed? (Error

Utilizing the 'soft-assert' library (soft-assert library) allows me to implement assertions in my test steps without halting the entire test if any of them fail. While softAssertAll() command works effectively to verify all soft-assert at the en ...

How can I retrieve the handle for an item within a jQuery collection from within the success function of an .ajax() call?

I'm currently facing an issue with a jQuery ajax call that I have firing for each element in a collection identified by a specific jQuery selector. Here's a snippet of the code: $('.myClass').each(function () { $.ajax({ url ...

default radio option with pre-selected value

Below is a radio option list, but I'm having trouble getting the desired default selection on first render: <label class="radio normalFontWeight"> <input type="radio" name="Criteria" data-ng-value="EVERYONE_REVIEWED" data-ng- ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

Incorporate the use of OpenLayers into a Vue.js application

Can anyone share their insights on incorporating Openlayers into a Vuejs project? I'm looking to showcase various layers within my Vue app. Thanks in advance! ...

Is there a way to remove a particular map from Firestore?

In my Google Firebase setup, I have uniquely named each Map to serve as the index for every document. Using Vuejs (Javascript), I have structured it as follows: eQFelbD432T (Collection Name- user.uid) SKILLS (Document Name) ProjectManangement (Map Na ...

Struggling with D3.js Angular CLI where Scope disappears within the tick() function?

Hey everyone, I'm currently in the process of incorporating a D3 visualization network graph into an Angular CLI project (http://bl.ocks.org/mbostock/1153292) using the ng2-nvd3 component. Here's the Angular component: import { Component, OnIn ...

What is the best way to import assets from an NPM-powered package in a PHP composer-based package?

First and foremost, let's clarify that this is not a question about incorporating an NPM package as a dependency of a Composer package. Direct usage of NPM or a composer plugin can easily solve that issue. If we have loaded an NPM package as a depend ...

What is causing the data to be altered outside of the directive scope?

I am having trouble understanding why the data is changing outside the directive in the external div. I expected it to behave the same as in the controller because the external Div is not wrapped in a directive or controller. Therefore, it should remain un ...

Can you explain the significance of verbosity in a nodemon setup?

Can someone explain the verbose setting in my nodemon configuration and what impact it has on the project? { "verbose": true, "watch": "./server" } I have checked the readme file for nodemon, but it doesn't provide any information on this specif ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

It is essential for Jquery to properly evaluate the first JSON result, as skipping

I'm currently facing an issue where the first JSON result is being skipped when I try to evaluate a set of JSON results. Below is the Jquery code snippet in question: function check_product_cash_discount(total_id){ //check for cash discount ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

Configuration of an MVC-based web application

As a newcomer to web application development, I am currently working on building a web application using the Model-View-Controller pattern. My setup includes a MySQL database for the Model, JSP pages for the Views, and a DAO for the Controller. I am looki ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

Tips for accessing the TextField value when clicking a button event in React Material UI

I'm currently working on a feature where I need to retrieve the input value from a search TextField. Upon clicking the "Search" button, I aim to call an API using the search input. Here's my progress so far: const handleSearchSubmit = async () =& ...