The `indexOf` method is incorrectly returning -1 despite the value being found within the array

I am facing an issue with the indexOf function in my code. I have a collection called placeCollection which contains an array named locFrnd. Since I couldn't use the indexOf function directly on the locFrnd array of objects, I created a new array called dup to store the data for performing the desired operations. The incoming data source is $scope.Friend, which is also an array that may contain multiple values. My goal is to compare each value in $scope.Friend with the values in the locFrnd array. If a value is not present in locFrnd, I want to push it into the array. The issue I am facing is that the indexOf operation is only referring to the last value in dup, which is causing unexpected behavior.

//if country exist
else if (cnt_exist == 1) {
    alert("country exist");

    var len = $scope.placeCollection[cnt_i].locFrnd.length;
    for (var j = 0; j < len; j++) {
        var dup = [];
        dup[j] = $scope.placeCollection[cnt_i].locFrnd[j].name;
    }

    //check for friend now
    alert("checking for friend");

    //some code has to be inserted here to handle Friends as it is an array  
    alert($scope.Friend.length);

    for (var k = 0; k < $scope.Friend.length; k++) {
        var frnd_exist = 0;

        alert($scope.Friend[k]);
        alert(dup.indexOf($scope.Friend[k]));

        if (dup.indexOf($scope.Friend[k]) != -1) // friend exist
        {
            alert("entered friend comparison");
            frnd_exist = 1;
        }

        if (frnd_exist == 1) // if friend does not exist
        {
            alert("friend exist");
        } else if (frnd_exist == 0) {
            var eachFriend = {
                name: $scope.Friend[k]
            }

            $scope.placeCollection[cnt_i].locFrnd.push(eachFriend);
        }
    }

Answer №1

The solution is clear.

Make sure to initialize dup before the for loop, instead of inside it.

let dup = [];
for (let k = 0; k < length; k++) {
  dup[k] = $scope.placeCollection[cnt_i].locFrnd[k].name;
}

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 steps can we take to perform queries within the context of a specific element in a Jest test?

Currently, I am in the process of writing Jest tests for a React application. Imagine that there is a webpage with multiple instances of a specific element present. For instance, let's consider a scenario where there are two buttons on the page. My ob ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

I'm having trouble getting a http.request to run within an imported module. It just doesn't seem to work when I try to access

Here is the code from my main.js file: var spaceJson = require('./space.js'); var options = { "method": "GET", "hostname": "10.10.111.226", "port": null, "path": "/API/Org", "headers": { "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJ ...

Exploring the POST method functionality in AJAX

I am having trouble creating a function that uses AJAX. When I try to send information using the POST method, the function does not work, but it works fine with the GET method. Here is the function: function ajaxFunction(page,metho ...

What is the best way to verify the [routerLink] values displayed from an Angular component string array?

I want to display the [routerLink] values coming from a string array in my Angular component. This is the TypeScript code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: & ...

Cross domain requests with jQuery's getJSON function

Struggling to fetch data using jQuery Cross Domain from GitHub, but hitting a roadblock! I've come across suggestions to use jsonp requests, but can't seem to figure out what's going wrong. http://jsfiddle.net/jzjVh/ Chrome seems to be int ...

Steps for bundling a Node server with an Electron application

I am looking to package my Electron app, built with React.js, along with a local Node server into a single executable file. Is there a way to ensure that the separate Node server runs simultaneously with the Electron app when the program is executed? ...

Texture on plane is not displaying properly in Three.JS

Seeking assistance! I've been struggling all day to successfully load a texture onto my plane in Three.JS. Every time I attempt to add the desired link, it either fails or *poof* my plane disappears mysteriously. Please lend me your expertise with Thr ...

Create a PHP function that takes in an array of positive numbers as input and outputs the largest number in the array. If the array is

I have been working on a PHP function that takes in an array of positive numbers and should return the largest number from the array. If the array happens to be empty, then it needs to return 0... Here is what I have attempted so far: <?php function ge ...

React js experiences a crash when it attempts to re-render with a different number of child elements

When working with react.js, I came across the need for a component that renders a 'tr' with either one or two 'td' elements, depending on its property. Here is an example: var Item = React.createClass({ content: function() { ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

React - the function executed within a loop is only invoked once

I have implemented a click handler in my book component to facilitate page flipping. This handler appends the necessary classnames to the pages, enabling me to set up the CSS for the page flip animation. // ---------- Handle the click event on the book p ...

Prevent multiple requests on jQuery infinite scrolling

I have implemented pagination on my website where the next page is loaded automatically when the user reaches the bottom of the page. This is achieved by using jQuery's .on('scroll', this.detectScroll()) method which triggers a function to l ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Execute angular.js as a callback function, such as within a $.ajax call

In developing my app, I am primarily working with two key JavaScript files: resources_loader.js and app.js. The role of resources_loader.js is to load some JSON files that are utilized by app.js. However, the issue arises when considering the sequence in ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

What are the best strategies for enhancing the performance of the jQuery tag:contains() selector

My goal is to extract all elements from a webpage that contain a specific set of words. For example, if I have an array of random words: words = ["sky", "element", "dry", "smooth", "java", "running", "illness", "lake", "soothing", "cardio", "gymnastic"] ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

Send submitted form field arrays to the database

I am currently developing a sewing management app that includes an order page where users can place multiple orders. However, all orders need to be invoiced with one reference code. On the first page, I collect basic details such as pricing, and on the nex ...