I have implemented a code snippet that verifies if the incoming week aligns with the existing week, triggering an alert accordingly

One of the challenges I faced was checking if a newly created week matched with an existing one, and then displaying an alert. Here's how I approached it:

$scope.addWeek = function(type,newWeek,index){
    var c = $scope.weekList.length + 1;
    var newWeek = {"weekName":newWeek,"modifiedTime": $filter('date')(new Date(), "h:mm a MMM d, yyyy")};

    var weekList= $scope.weekList;
    for(j=0;j<weekList.length;j++){
        if(weekList[j].weekName == newWeek){
            alert("The week already exists.");
            $("#"+ type + "weekmodalpopup").modal('toggle');
        }
        else {
            $scope.weekList.splice(0, 0, newWeek);
            $("#"+ type + "weekmodalpopup").modal('toggle');
        }
    }

// $scope.weekList.splice(0, 0, newWeek);
// $("#"+ type + "weekmodalpopup").modal('toggle');
};

Answer №1

One thing to keep in mind is that using the name 'newWeek' for both a function parameter and a local variable can lead to confusion. In this scenario, when you assign an object to this variable and compare each element of weekList with it, the comparison will fail due to object references. The newly created object is only referenced by the variable newWeek.

To address this issue, consider renaming either the local variable to newWeekObject or the function parameter to

newWeekName</code. I would suggest renaming the function parameter since the local variable is not necessary here.</p>

<p>In addition, the current approach of looping through <code>$scope.weekList
and comparing each element's name with
newWeekName</code seems flawed. At every step, you are either showing an alert or adding a new element to the array, which causes the array's length to increase and results in an infinite loop.</p>

<p>A better approach would be to use the <code>Array#some
method to check if the target week exists before deciding whether to insert a new week into the list. Here is an example:

$scope.addWeek = function(type, newWeekName, index) {
  var weekExists = $scope.weekList.some(function(week) {
    return week.weekName === newWeekName;
  });
  if (weekExists) {
    alert("The week already exists.");
  }
  else {
    $scope.weekList.unshift({
      weekName: newWeekName,
      modifiedTime: $filter('date')(new Date(), "h:mm a MMM d, yyyy")
    });
  }
  $("#" + type + "weekmodalpopup").modal('toggle');
};

In this code snippet, unshift is used instead of

splice(0, 0)</code for simplicity. If you wish to insert a new week at a specific index, you can replace it with <code>$scope.weekList.splice(index, 0, { ... }
.

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

What is the method for determining the angle between two planes?

My question is about calculating the angle between two planes. Is it also possible to calculate the angle between two Object3D points like we do with planes? If you need a visual example, check out this fiddle: https://jsfiddle.net/rsu842v8/1/ const ...

Understanding the Process of Accessing Array Values in Immutable.js

I'm feeling a little puzzled and struggling to figure this out. Let's say I have the following code: const AnObj = Immutable.Map({ a : "a", b : Immutable.List.of( a, b, c, Immutable.Map({ a : "a" }) ) }); When working with Immu ...

Having difficulty encapsulating three.js rendered particles within a single div

I'm facing an issue where the particles generated by my three.js project are not contained within a specific div or html element as intended. Instead of staying within the designated boundaries, the particles are spreading across the entire DOM witho ...

Facing Hurdles in Starting my Debut Titanium Mobile Project

I recently started using Titanium Studio (version 2.1.0GA on WindowsXP) and I have added the Android SDK to it. However, I am encountering an error when trying to run my first mobile project. The console is displaying the following message: Can anyone off ...

The search for 'partition' in 'rxjs' did not yield any results

Recently, I attempted to incorporate ng-http-loader into my Angular project. After successfully installing the ng-http-loader package, I encountered an error during compilation. The specific error message displayed was: export 'partition' was ...

The output of an Angular factory function is consistently null

I am facing an issue with storing the currentUser object in a factory to make it accessible throughout my app. Despite ensuring that the user object is being received server side, whenever I call CurrentUserFactory.GetCurrentUser(), it returns null inste ...

Ways to obtain the coordinates that surround a particular x, y location

I am trying to figure out how to generate an array of coordinates around a specific x, y point. For instance: xxxxx xxoxx xxxxx In this case, "o" is located at coordinates 3, 2. Now I aim to produce: xxx xox xxx as the set of coordinates surrounding "o ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

Horizontal line chart in Chart.js or a customized version of the horizontal bar chart

I'm currently using chart.js to create a timeline showcasing events in relation to the current date. While the horizontal bar chart is useful, I would prefer displaying only the tips of the bars as points essentially transforming it into a horizontal ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

Enhance a path SVG component with properties for a map in a React application

My goal is to develop a strategy game using an SVG map that I have created. I want to include attributes such as "troops" in each "path" representing territories, along with other properties. Can I add these attributes to individual paths and then use this ...

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

Issue with BrowserRouter, improperly looping through the array using map

Encountering an issue with importing content in my React app project using <BrowserRouter>. Within the app, there are 3 Material-UI Tabs: /lights, /animations, /settings. <Switch> <Route path="/lights" component={LightsMenu} /> ...

Implementing Formik in React for automatic updates to a Material-UI TextField when blurred

Presently, I am developing a dynamic table where users can simultaneously modify multiple user details in bulk (Refer to the Image). The implementation involves utilizing Material-UI's <TextField/> component along with Formik for managing form s ...

Tips on sending an array to material-ui dataSource props

Currently utilizing material-ui for a component. I am facing an issue with the autocomplete component in material-ui where I intend to display a list of icon names along with the icons. When only passing MenuItem to dataSource, it results in an empty input ...

Ways to Soothe Long Polling

Currently, I am developing a basic chat feature using AJAX in a function that triggers a setTimeout call to itself upon successful execution. This occurs approximately every 30 seconds. While this setup serves its purpose, I am seeking a more immediate not ...

Transferring data from a table to another window

Currently, I am retrieving values from a database and displaying them in a table. I would like to add a button to each row that will allow users to view more details about that specific row. At the moment, only ThesisID, AuthorID, and Title are visible. ...

Discover how to retrieve the calculated percentage within CSS with the assistance of jQuery specifically designed for Webkit

I'm currently working on a simple sliding animation. However, the div that slides in is utilizing percentages for its width and right positioning. The issue arises specifically in Webkit browsers. When using jQuery to retrieve the value, it returns t ...

Inject a dynamic URL parameter into an iframe without the need for server-side scripting

I'm really stuck and could use some assistance with the following issue, as I am unable to solve it on my own :( When a user is redirected to a form (provided via an iframe), there is a dynamic URL involved: website.com/form?id=123 The code resp ...

The login form using Ajax and PHP is experiencing an issue where the response is consistently empty

I am having issues with my login form. Every time I enter a login and password, whether correct or incorrect, the JavaScript script returns an error and the "response" is empty when I try to print it. Can anyone offer assistance? $(document).ready(funct ...