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 an image selection feature using ejs and express: a step-by-step guide

As I develop a blog site with a unique post management system using node, express, moongoDB, and EJS, everything seems to be running smoothly. However, the challenge arises when attempting to integrate Cloudinary uploaded images from my mongoDB to allow fo ...

AngularJS does not update values properly if there is a style applied to the parent container

I'm struggling to find the best approach to handle this situation. This is how my AngularJS code looks: <span class="something" ng-hide="onsomecondition"> {{value}} </span> .something{ text-align:left; padding:10px;} Issue: The value ...

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

What is the best way to specify the stream responseType for my client?

Is there a way to download a file from my express js app using AJAX instead of server-side handling? const response = await Axios({ method: 'GET', url: url, responseType: 'stream' }) Instead of piping the data directly to ...

jasmine and protractor test failing due to use of byID

My HTML markup is all set and valid. While using WebStorm to debug my test cases, I am able to view this specific element without any issues... <a id="privacyPolicy1234" on-tap="goPrivacyPolicy()" class="disable-user-behavior">Privacy Policy</a&g ...

Before you start interactivity in three.js, you will be presented with a classic

Recently, I incorporated a 3D WebGL viewer into my website, but I encountered a minor problem. Although everything functions properly and I am able to manipulate the object, there is a brief moment of a black screen upon loading the page before moving the ...

How to link an external CSS file to a Vue.js project

I created a new project using @vue/cli and now I want to add an external CSS file to my App.vue Here's what I attempted: <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | ...

Read and manipulate website content using PHP

I recently encountered a challenging situation as a newcomer. Despite searching on Google, I couldn't find any information about it. There is a website that allows users to search for doctors in their area or state. It's possible that the number ...

The functionality of AngularJs routing does not seem to be operating as anticipated

Please check out my demo example on Plunker. I have been experimenting with integrating the AdminLTE template with AngularJs Routing. I have defined the routing rules in my app.js file as follows: app.config(function ($routeProvider, $locationProvider) { ...

window.onresize = function() { // code here

Here's an example of code I've been working on: $(document).ready(function (e) { adjustSize(); $(window).resize(adjustSize); function adjustSize() { var windowWidth = parseInt($(window).width()); if (windowWidth > ...

Different placeholder text rendered in two text styles

Can an input box placeholder have two different styles? Here's the design I have in mind: https://i.stack.imgur.com/7OH9A.png ...

Monitoring progress with Angular $http and $q

Is there a method to monitor the progress of http requests using Angular's $http and $q services? I am sending multiple $http calls from a list of URLs and then utilizing $q.all to gather the results of all the requests. I want to keep track of the pr ...

Revamp local route variables in Express.js without the need for a page refresh

Currently, I am working on a project using node.js along with the express.js framework and EJS for template handling. Below is my routing code: app.get('/',function(req,res) { res.render('index', { matches: [], status_messag ...

Explore Youtube to find the most popular video IDs

Is it possible for me to use a string to search YouTube and retrieve the id for the top video in the search results? I want to be able to play that video directly on my website. All I have is the URL for the search: youtube_url/results?search_query=thevid ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Working with dynamic checkbox values in VueJS 2

In my project using VueJS 2 and Vuetify, I am creating a subscription form. The form is dynamic and fetches all the preferences related to a subscription from the server. In the example below, the preferences shown are specifically for a digital magazine s ...

Arranging a dictionary by its keys and transforming it into an array

Managing real-time updates on prices and quantities can be challenging, especially when dealing with large amounts of data. I have found that storing this data in a dictionary provides faster access compared to an array. let mainPriceValDict = [Double:Do ...

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

Perform the cloning process for each item listed in my JSON file

I'm trying to display a list of names from a JSON file on my webpage, each in their own separate div. However, I've been unsuccessful in getting it to work so far. Currently, this is what I have attempted: var cloneTeam = $('.team').c ...

Is there a way to incorporate locales in calculations involving percentages?

Given the number 4030.146852312 I want to retrieve the four decimal places from this number, resulting in: 4030.1468 Furthermore, I need to format this number according to the specified locale. For example: 4.030,1468 What is the best way to achieve thi ...