Locate a particular word in every element within an array range (angularjs)

I'm just getting started with learning angularjs and I would appreciate some kindness as a beginner.

Currently, I am working on creating a poll app using angular.

In my project, I have an array scope named items, which holds all the items to be added to the poll.

$scope.items = []

I am writing an error handling script to let the user know if a specific poll item already exists in the items array. Due to the format of how my items are added (e.g., 1. item1, 2. item2), I cannot directly use the indexOf method in the array to search for existing items. Instead, I need to loop through all indexes in the items[] array and perform the indexOf method within each index to check for duplicates.

The code I have should return true if an item is found in the array and false if it isn't:

    //number of items in the array
    var itemNum = $scope.items.length + 1;
    //the item entered by the user
    var toBeAdded = $scope.pollItem;

    //search for existing item in items[] array
    var findItem = function (){
        for (var i = 0; i < itemNum-1; i++) {
            if ($scope.items[i].indexOf(toBeAdded) >= 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    //add the item to the poll if findItem() returns false
    if (!findItem) {
        $scope.items.push(itemNum.toString() + " " + toBeAdded);
        $scope.pollItem = "";
        focus('pollItem');
    } else {
        alert('item already exists');
    }

However, this code always returns "true" even when my items array is empty. I can't figure out what I'm doing wrong. Any help would be greatly appreciated.

Thank you to anyone who can assist me.

Answer №1

If you define a function using var findItem = function() {...}, remember to call it with findItem(). Otherwise, the function won't be executed. Since findItem is not null, !findItem will always evaluate to false because JavaScript recognizes findItem as a variable.

To fix this issue, change if (!findItem) to if (!findItem()).

Please see the code snippet provided below for reference:

var items = [];
var toBeAdded = {
  test: 'test'
};
var findItem = function() {
  for (var i = 0; i < items.length - 1; i++) {
    if (items[i].indexOf(toBeAdded) >= 0) {
      return true
    } else {
      return false
    }
  }
}

if (!findItem()) {
  items.push(toBeAdded);
} else {
  alert('item already exists');
}
console.log(items);

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 and deleting HTML elements in a dynamic array format

My current approach involves utilizing jQuery and JavaScript for the purpose of dynamically adding and removing HTML elements. Specifically, I am focusing on the removal of particular HTML elements. The code snippet is as follows: $(document).ready(fun ...

Angular's ng-disabled feature seems to be experiencing a delay in functionality

While editing the file, I have the ability to modify the filename and add additional files for versions. Once a file has been chosen, the filename edit field should be disabled immediately. Despite attempting the following code, the field remains enabled u ...

Using default JavaScriptSerializer to bind DateTime to knockout view model

Recently, I started using knockout and encountered a problem with DateTime Serialization and Deserialization when using the JavaScriptSerializer. I modified the gifts model in Steve's koListEditor example from his blog to include a new field for Modi ...

React.js JSX side by side components

When running the code below, I encounter an exception related to parsing in React. How can I resolve this error where JSX elements must be wrapped in an enclosing tag? Error: Line 48: Parsing error: Adjacent JSX elements must be wrapped in an enclosin ...

Is there a way for me to update a Link To containing a parameter by using history.push with a parameter inside a table cell?

Hey there! I'm working on some code and wondering if it's doable to replace the Link To with a history.push, including the following parameter, like so: <TableCell style={{width: '10%'}}> <Link to={`/run-id/${item.run_ ...

Incorporating AngularJS Controller to Render Asp.Net MVC 5 View

I am attempting to navigate to the Home page once a user successfully logs in. My current tech stack includes ASP.NET MVC 5, AngularJS, EntityFramework 6, Bootstrap, and repository pattern. Below is the code snippet from my LoginController: public JsonRes ...

What is the best way to identify a specific AdWords account while utilizing campaignSelector within AdWords scripts?

I have been working on a script that aims to achieve the following tasks: Go through all the accounts in an MCC and pick out the ones with 'SEM' in their name. Go through the campaigns in a selected account and choose those that meet specific c ...

What is the best way to transform a collection of items into FormData?

In my current project, I have a JavaScript array structured as follows: var items = [{ ID: "1" count:'1', File: (binary file) }, { ID: "2" count:'2', File: (binary file) } ] My goal is to ...

"The changes made to the list are not being accurately displayed by Angular's ng

I am working on a directive that injects dynamic templates during ng-repeat. While I can successfully add items to the list, they do not appear in the view for some reason. It seems like I am missing a crucial piece to make it work correctly. You can find ...

Trouble getting CSS to load in Webpack

I'm having some trouble setting up Webpack for the first time and I think I might be overlooking something. My goal is to use Webpack's ExtractTextPlugin to generate a CSS file in the "dist" folder, but it seems that Webpack isn't recognizi ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...

I attempted to create a test scenario to verify that the length of the tasks array is not negative. However, when trying to test this using 'not.toBe' in the code below, an error was encountered

app.js var todos=[]; todos=['to-do one', 'to-do two']; module.exports=todos; app.test.js const todos=require('./app') test('should have a length of at least 0',()=>{ expect(todos.length).toBeGreaterThanOrEqu ...

`Vue Component failing to display data from Blade File`

In my project using Laravel Blade, I am currently in the process of converting some blade files to Vue components. One challenge I encountered is trying to display a dynamically created page title on the screen from the Vue component rather than the blade ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

Pass PHP array to a JavaScript file using AJAX

Starting with a basic knowledge of PHP and AJAX, I was tasked with creating a form that prompts the user to choose between two car manufacturers. Upon selection, the form should display all models of the chosen make from a multidimensional array stored in ...

Is there a way for me to determine if the HTML code is creating a new line?

Here is my code snippet: <div id="box"> <p> 123 </p> <p> abc </p> </div> <script> var html = document.getElementById("box").innerHTML; for (var i = 0, len = html.length; i & ...

Update the color of the text depending on the background color

When hovering over my CTA, a sliding effect occurs. However, I am facing an issue with the text being difficult to read depending on the background color. To better understand what I'm trying to achieve, you can view the demo here: Demo on CodePen T ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...

Attempting to create a JavaScript function that will show a JSON array when the next button is clicked

I am facing an issue with displaying a JSON array based on specific start and end indices. Even though I managed to display the entire array, the first button click does not seem to work as expected. Upon clicking the first button, an error message "this.d ...

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...