Output either TRUE or FALSE from a function

Within this function, I am working with an array of objects and a specific value. The function iterates through the array using a forEach method to check if the provided value already exists in any of the objects within the array. If it is found, it should return FALSE; otherwise, it will return true. However, even when it returns FALSE, the rest of the code gets executed which leads to TRUE being returned all the time. How can I ensure that only FALSE/TRUE is returned?


if(find_value_in_obj(all_selected,current.value)){
    all_selected.push({select_elem:current,value:current.value});
    console.log(all_selected);
}else{
    alert("you already selected the value");
}

function find_value_in_obj(arr_obj,value){
    arr_obj.forEach(function(elem,index,array){
        if(elem.value == value){
            console.log('found it ');
            return false;
        }
    });
    console.log("i am here"); // although the value already exists and should be returned, this line gets executed resulting in returning TRUE instead
    return true;
}

Answer №1

The forEach method loops through all values in an array. Consider using the .some() method.

Instead of creating a helper function for the .some() method as shown in this example from MDN, you can directly use it in a one-liner:

console.log([2, 5, 8, 1, 4].some(elem => elem > 10));  // false
console.log([12, 5, 8, 1, 4].some(elem => elem > 10)); // true

Answer №2

forEach does not support breaking in the middle of its iteration like a traditional for loop. It is recommended to use a regular for loop instead. Alternatively, if you are using ES6, you can achieve the same outcome by using .find().

function find_value_in_obj(arr_obj,value){
   return !!!arr_obj.find(itm => itm == value);
}

Another approach suggested by Felix is to utilize Array.prototype.some.

function find_value_in_obj(arr_obj,value){
   return !arr_obj.some(itm => itm == value);
}

Answer №3

If you're looking for a cleaner solution, consider using the filter method in your code.

   if(find_value_in_obj(all_selected,current.value)){
    all_selected.push({select_elem:current,value:current.value});
    console.log(all_selected);
}else{

    alert("you already selected the value");   
}

function find_value_in_obj(arr_obj,value){

    var resultArray = arr_obj.filter(function(elem,index,array){
        return elem.value == value;
    });

    if(resultArray.length > 0){
       return false;
    }
    console.log("i am her"); // even though the value already exists and should be returned, this line gets executed resulting in returning TRUE instead

    return true;
}

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

The Ajax code fails to refresh the document object model

I've encountered a small issue with my Ajax script that performs a POST request and displays the result on the screen. Even though the POST request is successful, I'm not able to view the result on the screen. It seems like there might be a need ...

The output from VScode-Code-Runner is limited to just the directory, with no additional

I have successfully set up Code Runner with the following configurations in the Executer Map: { "explorer.confirmDelete": false, "[html]": { "editor.defaultFormatter": "vscode.html-language-features" }, "[javascript]": { "e ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

In Typescript, define a class with a property that will serve as the name of another type's property

Trying to define a class property for another type: class TypeOne { public static readonly code: string = 'code'; } class TypeTwo { public [TypeOne.code]: TypeOne } Encountering an error message: The computed property name in the class pr ...

How can you display an alert message when new data is successfully added to a database using ajax?

In my web application, I have implemented a functionality to display an alert message when new data is successfully inserted into the database. The Ajax code below is responsible for sending a request to the EditDeleteLecture.php file. However, a challenge ...

Updating Elements of a Row in a Two-Dimensional Array with For Loops

I am having trouble implementing a function called zero_row. This function is designed to insert the value of zero into a specified row in an array. The function requires two variables to be passed: a (the array) and row (the row in the array). Below is th ...

Sequencing when employing v-for

When utilizing the v-for to loop through an array as shown below: <ul id="example-1"> <li v-for="item in items"> {{ item.message }} </li> </ul> The items are displayed vertically as follows: Item 1 Item 2 Item ... Item ...

Display an array table in PHP depending on the specific option selected in a form

I am currently working on a project where I need to display an array table based on user input from a form. The issue is that even though I have the filtering working, there are still empty rows for results that are not displayed. Is there a way to hide or ...

The information sent via POST (via fetch JavaScript with PHP8) is not being received by PHP8

My PHP8 server is not receiving the data I am sending. When trying to insert a new song into my API, an error occurs and in the console, I see an object with POST as an empty array. fetch("http://localhost/api.audio-player/",{ method: 'POST&apos ...

Utilize a service within a different service in the same module with code reference #1250

Within module A, I have two services/providers. The first is called ServiceA1 and is marked as @Injectable(). The second service/provider is named ServiceA2, also marked as @Injectable(). I am attempting to inject ServiceA1 into ServiceA2 using the follow ...

Combine HTMLPlugin with react-chartjs-2 version 4

I'm attempting to implement a customized Label using a plugin with react-chartjs-2. Here are the versions I am currently using "chart.js": "^3.9.1", "react-chartjs-2": "^4.3.1", "chartjs-plugin-datalabels& ...

What steps can I take to resolve the CLIENT_MISSING_INTENTS issue?

After diving into learning about discord.js, I've run into a bit of a roadblock. Despite trying to troubleshoot by searching online, I can't seem to resolve the issue. const Discord = require('discord.js'); // const Discord = require(&a ...

Ways to precisely define a matrix of type Integer[][] in a coding scenario

It's an easy question for someone skilled in this. Create a two-dimensional array named 'res' with some hard-coded values like the following: Integer[][] res = new Integer[][] {.....hard code some values here on 2 dim...} How can you modif ...

Error encountered while attempting to load the vue-sanitize plugin within a Vue.JS application

Hi everyone, I'm encountering a problem with a plugin in Vue that I'm hoping to get some help with. Specifically, I am trying to incorporate vue-sanitize (available here: https://www.npmjs.com/package/vue-sanitize) into my project, but I keep re ...

Having trouble retrieving data from fetch operation

Having trouble with pulling and displaying search results on the Left page using the SearchFilms component? The API key has been deliberately removed, making it difficult for beginners to figure out what to do. Where should we start? import React, {Fragm ...

Encountered a JSON error while implementing in an ASP project

Currently, I am working with JavaScript and C# in aspnet. My goal is to pass 3 values from the Asp Page to the code behind, using the Json method. Below is how I achieve this: //initialize x, y and nome var requestParameter = { 'xx': x, 'yy ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...

What is the process for converting a JSON file into a Java 8 Object Stream?

I have a confidential JSON file larger than 1GB that contains an array of data related to sleep durations. Here is a simplified version: [ { "date": "August 17, 2015", "hours": 7, "minutes": 10 }, ...

How come I'm getting a numerical output instead of an array after using the array.push() method in this code?

In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in ...

Running an HTML form that originates from a JavaScript GET Request

When attempting to call an API, I received a HTML response containing an auto-submit form triggered by the onload event. How can I submit this form retrieved from the API response? The jQuery function used: $.get( "example.html", function( data ) { ...