Instead of pushing multiple items, focus on pushing only one item at a time

I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist.

However, instead of adding the new item only once, it ends up being added multiple times.

What would be the most effective approach to resolve this problem?

Thank you in advance!


$scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
    console.log($scope.favlist);

    $scope.toggleStar = function(item) {
      item.star = !item.star;
      console.log(item); //object


      var favlistcontent = $window.localStorage.getItem("favlist");
        console.log(favlistcontent); //string

        if(typeof favlistcontent !== 'string'){
         $scope.favlist = [];
         $window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
       }
       $scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
      console.log($scope.favlist); //object
      console.log($scope.favlist.length);

      console.log(angular.equals($scope.favlist[0],item)); //true
      for(i=0; i<$scope.favlist.length; i++){
        if(angular.equals($scope.favlist[i],item)){
          console.log("item already exists");


       }
       else {
        $scope.favlist.push(item);
        $window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
      }
    }

Answer №1

To ensure that the loop stops once it finds a matching item, simply set a flag to true when a duplicate is found and break out of the loop at that point.

var isDuplicate = false;

for (var index = 0; index < $scope.favoriteList.length; index++) {
    if (angular.equals($scope.favoriteList[index], newItem)) {
        console.log("Item already exists in the list");
        isDuplicate = true;
        break; //exit loop
    }
}

if (!isDuplicate) {
    $scope.favoriteList.push(newItem);
    $window.localStorage.setItem("favoriteList", JSON.stringify($scope.favoriteList));
}

Answer №2

To address this issue effectively, utilize the following solution:

  if($scope.favlist.indexOf(item)==-1){
    // item is not a duplicate
    $scope.favlist.push(item);
    $window.localStorage.setItem("favlist", JSON.stringify($scope.favlist));
  }

The comparison appears to be much simpler. In modern browsers, the indexOf function tends to have superior performance compared to manually looping through items.

For more details and a performance comparison, refer to this benchmark: https://jsperf.com/js-for-loop-vs-array-indexof/10

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 HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

What is the best way to explain the concept of type indexing in TypeScript using its own keys?

I'm still learning TypeScript, so please bear with me if my question sounds basic. Is there a way to specify the index for this type so that it utilizes its own keys rather than just being an object? export type TypeAbCreationModal = { [index: stri ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

What are the benefits of using React.useMemo or React.useCallback within component props?

Exploring efficient ways to implement TailwindCSS in React, considering its utility-first nature leading to component-heavy code (e.g. className="w-full bg-red-500"). One approach is creating a utility function like: utils/tailwind.ts const tw = (...clas ...

Using finally() to correctly construct a Javascript promise

Currently, I am working on an Express API that utilizes the mssql package. If I neglect to execute sql.close(), an error is triggered displaying: Error: Global connection already exists. Call sql.close() first. I aim to keep the endpoints simple and e ...

Create dynamic combo boxes using jQuery

My goal is to display a text field on the page if a user has only one credit card number in the database. However, if the user has multiple credit card numbers stored, I want to display all of them in a combo box. Below is the ajax response that I am rece ...

Trouble with Metro UI Library: CSS not loading properly

I am having trouble with the navbar CSS on my website while using the Metro UI CSS library. Check out my HTML code: <!DOCTYPE html> <html lang="en"> <head> <title>TelePrint Blog</title> <link rel="stylesheet" href= ...

Swift: Comparing the functions of addingObjects method versus the append method

I'm in the process of learning Swift 3 for iOS development and I was curious about the distinction between these two methods: if let myItemArray = itemObject as? NSArray { myItemArray.addingObjects(from: [itemTextField.text!]) ...

Constructing an extensive modular application using the AngularJS and RequireJS framework

I'm embarking on the creation of an extensive Modular Web App using AngularJs and RequireJS. Here is the directory structure I envision: |--index.html |--css |--images |--libs | └--angular.js | └--angular-route.js | └--require.js | |--js | ...

You can activate Lightgallery just one time in VueJs

I am facing an issue where lightgallery can only be opened once. Subsequent clicks on the button are unresponsive. The lightgallery is being used as a component. Within my parent component, I have two buttons for opening image or video gallery ParentComp ...

Learn how to utilize Jquery to create a dynamic slide effect that toggles the

I am looking to change a banner on click functionality. Currently, I have hidden the 2nd banner and banner 1 is displayed. When the arrow is clicked, I want banner 1 to hide and banner 2 to show. The challenge is that I attempted using HTML for this task. ...

Preloader will properly handle websocket connections along with pace js

I recently implemented a preloader on my website built with Ruby on Rails. Everything seems to be working perfectly, except for the fact that due to Pusher websockets, the preloader does not stop and keeps running indefinitely. I attempted to address this ...

Express displaying undefined when referring to EJS variable

After receiving valuable assistance from user Jobsamuel, I have been encountering challenges in displaying the data retrieved from an API call on a webpage: // EJS template to show API data. app.get('/activities', function (req, res) { if (re ...

Tips for saving an array of objects in local storage and transferring it from one file to another

Recently delving into the world of localstorage, I've encountered an issue while attempting to store JSON data in one file and retrieve it in another. The JSON data below was fetched from a URL, and my goal is to obtain all the feed objects in the oth ...

How to Send Data to AngularJs Controller via Parameters

Starting out with AngularJs and trying to figure things out. On my details page, I am displaying a link as shown below: <a href='/device-summary/"+ full.link.href+"'>"+ data_to_be_displayed+"</a> In the provided link, full.link.href ...

The model of a controller in an isolate directive is not able to be accessed in the view

!!!!!!!!!! Outdated Query Take a look at the code (Not Current). The standalone directive with template is functioning, but the one utilizing it in the display isn't. The Latest Inquiry I am using the same plunk and I have followed @Andrew Eisenb ...

AngularJS UI-calendar fails to display updated events on Calendar

I am currently using Angular UI-Calendar to display events on the Calendar. The events are appearing correctly on the Calendar, but when I update the details of an event, the changes are not reflected in the Calendar display (for example, the start date). ...

Is there a method to compress all of my JS/CSS files before displaying them in the browser without doing so while editing them in the IDE?

I have a JavaScript file with numerous comments and unnecessary spaces, making it larger and slowing down the website. I am seeking a solution to minify the file when starting the server, while still being able to edit the original file in my IDE. Essen ...

Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element ...

How can I incorporate percentage values into input text in Angular?

How can I include a percent sign in an input field using Angular, without relying on jQuery? I am looking for a solution that is identical to what I would achieve with jQuery. Here is the current status of my project: ...