Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango"
let fruitArray = [{fruit:"apple",locale:"US"},
        {fruit:"orange",locale:"US"},
        {fruit:"banana",locale:"US"},
        {fruit:"apple",locale:"US"},
        {fruit:"orange",locale:"IT"},
        {fruit:"apple",locale:"MX"},
        {fruit:"banana",locale:"FR"},
        {fruit:"orange",locale:"IT"}
        {fruit:"apple",locale:"MX"}]

Given the variable "selectedFruit" representing a fruit, I am looking to find if the fruit exists in the "fruitArray" with the same locale set to "US". If it does, I want to set a flag to true; otherwise, set it to false if the fruit exists with a different locale in the array.

for (let i = 0; i < fruitArray.length; i++) {
            if (fruitArray[i]["fruit"].toString().toLowerCase() === selectedFruit.toString().toLowerCase() && fruitArray[i]["locale"] === "US") {
                this.uniqueFruit = true;
                break;
            } else {
                this.uniqueFruit = false;
            }  
        }

The code above checks if the "selectedFruit" exists in the array of objects. However, the question remains on how to validate if the fruit exists in the array with the same locale set to "US".

Answer №1

To enhance your loop, include a comparison of the locale in the following manner:

let selectedBook = "Harry Potter"
let library = [{book:"Harry Potter",genre:"fantasy"},
        {book:"Lord of the Rings",genre:"fantasy"},
        {book:"Pride and Prejudice",genre:"romance"},
        {book:"Harry Potter",genre:"fiction"},
        {book:"Lord of the Rings",genre:"fiction"},
        {book:"Pride and Prejudice",genre:"romance"},
        {book:"Harry Potter",genre:"thriller"}]

console.log(validate(library,selectedBook,"fantasy"));
console.log(validate(library,selectedBook,"fiction"));

function validate(array, selectedBook, genre){
     for(let i = 0; i < array.length; i++)
          if(array[i]["book"].toLowerCase() == selectedBook.toLowerCase() && array[i]["genre"] == genre)
               return true;
     return false;
}

Answer №2

To improve the code, consider including a property for desired fruits and another property depending on the locale setting.

let currentFruit = "apple",
    locale = "US",
    array = [{ fruit: "apple", locale: "US" }, { fruit: "orange", locale: "US" }, {fruit: "banana", locale: "US" }, { fruit: "apple", locale: "US" }, { fruit: "orange", locale: "IT" }, { fruit: "apple", locale: "IT" }, { fruit: "banana", locale: "IT" }, { fruit: "orange", locale: "IT" }, { fruit: "apple", locale: "IT" }]

array.forEach(o => {
    if (o.fruit !== currentFruit) return;
    o.uniqueFruit = o.locale === locale;
});

console.log(array);

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

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Simplified JavaScript Object Structure

A JSON array that is flat in structure looks like this: var flatObject = [ { id : "1", parentId : "0", name : "object 1" }, { id : "2", parentId : "1", name : "object 2" }, { id : "3", parentId : "2", name : "object 3" }, { id : "4", pare ...

Embrace the use of square brackets when formatting JSON output

Below is the current output that I am getting: {"name":"a","path":"a","type":"folder","items":{"name":"b","path":"a/b","type":"folder","items":{"name":"c.docx","path":"a/b/c.docx","type":"file","size":"20"}}} I want to modify it to add brackets in the "i ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

What is the recommended TypeScript type for setting React children?

My current layout is as follows: export default function Layout(children:any) { return ( <div className={`${styles.FixedBody} bg-gray-200`}> <main className={styles.FixedMain}> <LoginButton /> { children } ...

Effortlessly handle form submission with jQuery AJAX, automatically redirecting upon successful

I am working on a project using ASP.Net MVC where I have a view that submits form data to a controller action. In order to make this form submission more dynamic, I am trying to utilize jQuery to post the form via an AJAX call with the following code: $(" ...

Combining the redux toolkit function createAsyncThunk with Angular's HttpClient by leveraging the ApiService

Currently, I am working on incorporating @reduxjs/toolkit into an Angular project. Is there a way to pass an Angular service as a parameter to the callback of createAsyncThunk instead of utilizing fetch directly? I referenced the documentation for an exa ...

Constructing a React component with a constructor

I am brand new to working with react native and I'm requesting assistance in fixing the code below. Currently, I have a view within a const and I am looking to include a constructor inside the const function. const { width } = Dimensions.get(' ...

Assistance in configuring Zurb Foundation 5 for optimal integration with Laravel

As a relatively new user to Laravel with previous experience using older versions of Foundation, I am currently in the process of setting up a new Laravel project. My goal is to integrate the Foundation framework into my project, but I find myself a bit co ...

What is preventing me from retrieving WP custom fields value or post ID using Ajax?

After successfully generating a link based on the visitor's location, I encountered an issue with caching when using full-page caching. To address this problem, I decided to implement AJAX to dynamically load the link. While my code worked well in ret ...

Leverage the power of Angular's $http module in conjunction with Django's urlpatterns to fetch

I am attempting to send a $http GET request to a Django URL pattern in order to retrieve a .json file. Is it possible to use urlpatterns to return a file instead of a view? Is this scenario achievable, or are there limitations preventing this from working ...

Verify array ContainsIs235

Need help with verifying if an array is Is235 compliant? An array that qualifies as Is235 must contain an integer divisible by 2, another integer divisible by 3, and a third integer divisible by 5. In addition, any other integers in the array that are not ...

Extracting information from HTML and transferring it to Javascript using jQuery

My goal is to utilize jsGrid for showcasing database data without repeating code extensively. I aim to generate separate grids for each <div> with a specific id while passing on relevant values accordingly. To clarify my objective, here's a sni ...

Prepared SQL Statement in NodeJS for MSSQL using WHERE IN clause

I'm using the sql npm package in my Node.js project. Currently, I have an array of product SKUs like this: var skus = ['product1', 'product2', 'product3']; The SQL query stored in a file looks like this: SELECT * FROM ...

Pretending to determine the exact height of the body

I am facing a challenge with my JavaScript application that is loaded within an iframe through a Liferay portlet. The HTML container is currently empty and the JS is loaded only when the document is fully loaded. Upon loading the page in the iframe, Lifer ...

The error message "Access-Control-Allow-Origin header is missing on the requested resource" is still appearing despite having the correct CORS middleware set up

I am encountering the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource" despite having implemented the necessary middleware in my express server. Here is the code snippet of the middleware placed before ...

What is the process to include an image file in a JSON object using PhoneGap?

Having trouble saving an image in JSON. Managed to access the mobile camera with the provided code: var pictureSource; // source of the picture var destinationType; // sets the format of returned value // Wait for PhoneGap to connect with the device / ...

Displaying the HTML code for a dynamically generated table

Can the generated HTML code be retrieved when dynamically creating a table using v-for loops in Vue? <table> <tr> <th colspan="99">row 1</th> </tr> <tr> <th rowspan="2">row 2< ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...