Failure occurs when attempting to compare multidimensional arrays to locate the correct index for use in another multidimensional array

Hey there! I'm reaching out because I need assistance with a Javascript function:

Basically, I have an input array that I want to compare to another array and based on the result, return something. However, for some reason my comparison is not yielding the correct outcome...

Here's the function in question:

const createArrayColor = (labels) => {
  const combi = [
    ["bronze","gold","new","silver"],
    // Other array combinations listed here...
  ];

  const color = [
    // Corresponding colors for each combination mentioned above...
  ];

  let i = 0;

  combi.forEach((c) => {
      console.log("Color: " + color[i]);
      console.log("Combi:  " + c + " ,type:  " + c.constructor.name );
      console.log("labels: " + labels + " ,type:  " + labels.constructor.name );
      console.log("Is it equal? " + (labels === c));

    if (labels === c) {
      return color[i];
    }
    i = i + 1;
  })
}

(By the way, if you happen to know a better way to create combinations of arrays in JS, please share! I believe there might be a more efficient method than what I've attempted so far)

As evident from the code snippet provided, I am comparing the labels array with each element within the combi array, yet the comparison always results in false...

https://i.sstatic.net/Mp61j.png

I reckon it's just a minor oversight on my part, but alas, I'm unable to pinpoint where I went wrong...

Answer №1

The arrays "c" and "labels" contain identical elements but are distinct from each other. For guidance on comparing arrays in JavaScript, refer to this question.

Answer №2

If there is a need to retain the `forEach` iterator for some reason, it becomes necessary to iterate twice through the array as it is multidimensional with 2 depths.

This code snippet showcases finding the first occurrence for a given value:

const createArrayColor = (labels) => {
    const combi = [
        ["bronze","gold","new","silver"],
        ["bronze","gold","silver"],
        // Additional arrays trimmed for brevity
    ];

    const color = [
        ["#614E1A","#c49c48", "#f4f3f3", "#A5A49B"],
        ["#614E1A", "#c49c48", "#A5A49B"],
        // Additional arrays trimmed for brevity
    ];

    let i = 0;
    let foundColorValue;
    combi.forEach((combiArray, arrayIndex) => {
        combiArray.forEach( (combiLabel, labelIndex)=>{
              if(combiLabel === labels && foundColorValue === undefined){
                 foundColorValue = color[arrayIndex][labelIndex];
              }
        });
    });
    
    return foundColorValue;
}

let foundColor =  createArrayColor('silver');
console.log('found ' + foundColor);

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

Utilize jQuery to showcase a chosen cryptocurrency from coinmarketcap's API

I've been attempting to retrieve specific coin data from the Coinmarketcap API using JavaScript, but for some reason, nothing seems to be working. I'm really puzzled about where I might have gone wrong... var coin = "spectrecoin"; $.get("https ...

What is the best way to deploy a nodejs expressjs application to a server?

I have successfully developed a nodejs and express application that works perfectly on my localhost. To start the application, I simply run the command npm start or node index.js. Recently, I uploaded all the necessary files, including node_modules, to a ...

Laravel Tutorial: Passing a Specific Shop ID in a Foreach Loop to a Controller

I am trying to extract the specific shop id when the button is clicked. I have a foreach loop that displays the name of each shop and its products. What I'm aiming for is to pass the $shop->id value to the controller after clicking the x button. On ...

Displaying hyperlinks within a table that is contained within a div on the current webpage

I have created an HTML page that looks like this: <!DOCTYPE html> <html> <body bgcolor="#EBF5FB"> <h1 align="center">SLA Monitor Reports </h1> <div id="link" align="center"> <table cellpadding="25px" bord ...

Please disable zoom functionality on the website specifically for Android devices

Is there a way to disable the zoom feature on our website specifically for Android phones/devices without affecting iPhones? Perhaps targeting the Chrome browser on Android would be sufficient, but we should also verify the mobile screen size. ...

Creating personalized validation for an AJAX popup in the MVC framework

In my MVC project, I am trying to implement AJAX popup with custom validation. I have created a CustomValidator class and overridden the IsValid() method. However, I am facing an issue where the custom validations are not rendering correctly within the pop ...

Browsing a container with JavaScript

I am attempting to display one div at a time and scroll through them repeatedly. I found and modified a Fiddle that works as intended, but when I try to implement it on my own test page, the divs do not scroll as expected. Here is the Fiddle example: http ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Is there a way to directly set object parameters when a web page loads using JavaScript?

Is there a way to read params values directly into NPAPi plugin? Here is the current JS and form code: <script> var control = document.getElementById('embed'); </script> <form name="formname"> <input type=button value="In ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

How can I choose multiple criteria by utilizing the indexOf('EXAMPLE.com') method? Is there a way to add additional examples for selection?

I'm currently working on extracting specific usernames from a training portal: Up to this point, I've come up with some code that's able to select all emails containing EXAMPLE.com (as shown below) Is there anyone who could modify this cod ...

Changing content of inline editable data table in Vuetify through a method

I am facing a challenge while attempting to update the value in my inline edit data table from a method. The issue lies in the fact that the item I pass is not getting updated. In my cancel method, I pass props.item to be updated. While props.item.iron pr ...

replace the tsconfig.json file with the one provided in the package

While working on my React app and installing a third-party package using TypeScript, I encountered an error message that said: Class constructor Name cannot be invoked without 'new' I attempted to declare a variable with 'new', but tha ...

transmit JSON data with an AJAX request and receive a response

I'm looking to make a JSON request to an API and receive a response. I tested it using Postman and successfully received the following response: JSON request to API: { "apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp" } The response I receiv ...

Choosing an element from a multiple group listbox with jQuery

Is there a way to select items in the listbox using jQuery when dealing with optgroup elements? $('#id option[value=<?php echo $row; ?>]').attr('selected','selected'); The above code works for regular options, but how ...

What is the most efficient method for importing external geometries into Three.js without causing any interference with the user interface?

At this moment, I am facing an issue with loading multiple .obj files (totaling 20MB) into Three.js. Although everything works fine once the files are loaded, the main problem lies in the fact that it takes approximately 25 seconds for Three.js to proces ...

Initiate the function once the condition is satisfied (contains the class "in-view")

Here is the code for an animation: var setInter = null; function startAnimation() { var frames = document.getElementById("animation").children; var frameCount = frames.length; var i = 0; setInter = setInterval(function () { fr ...

Is it necessary to have both variables present in an if statement for it to be evaluated?

In an attempt to determine if a custom Date widget in JavaScript is empty or not, the following function is created. The challenge lies in the fact that there are multiple variations of this widget - some display M/D/Y fields, while others may only show M/ ...

I encountered a Content Security Policy error while utilizing Disqus on my Jekyll website

I recently created a website using Jekyll and it is hosted on Github Pages: Check out the site, View the repository Here is a snippet from Jekyll's _config.yml: # Comments disqus_shortname: bad3r You can find the Disqus configuration in the _layo ...

One way to display a div's inner HTML as its background is to apply a CSS rule

Help needed! <div class="container">red</div> <div class="container">green</div> <div class="container">#eeeeee</div> I am trying to dynamically set background colors for multiple divs based on their inner HTML co ...