Analyzing and contrasting two distinct arrays in Javascript

Is there anyone who can help me with this task? I am attempting to compare two separate arrays and push values when the comparison is equal. The arrays in question are imageslide (including therapy) and totalValues. My goal is to compare names like cats and dogs, and if a condition is met, I want to push their respective image URLs.


var imageslide = {
    "therapy": [
        {
            "name": "cats",
            "images": [
                { "url": "cat/firstimg.jpg" },
                { "url": "cat/secondimg.jpg" },
                { "url": "cat/thirdimg.jpg" },
                { "url": "cat/fourthimg.jpg" }
            ]
        },

        {
            "name": "dogs",
            "images": [
                { "url": "dog/firstdog.jpeg" },
                { "url": "dog/seconddog.jpg" },
                { "url": "dog/thirddog.jpg" },
                { "url": "dog/fourthdog.jpg" }
            ]
        },
    ]
}

var totalValues = ["cats", "dogs"];

I have attempted the following approach:


var imageArray = imageslide.therapy
function compare(imageArray, totalValues ){
    imageArray.forEach((e1) => totalValues.forEach((e2) => {
        if(e1.name == e2){
            console.log(e1.name, ",", e2)
        }
    })
}

Answer №1

Based on your inquiry, I have provided an answer using simple JavaScript since my knowledge of arrow functions is limited.

var imageslide = {
    "therapy": [
                    {
                        "name": "cats",
                        "images": [
                            { "url": "cat/firstimg.jpg" },
                            { "url": "cat/secondimg.jpg" },
                            { "url": "cat/thirdimg.jpg" },
                            { "url": "cat/fourthimg.jpg" }
                        ]
                    },

                    {
                        "name": "dogs",
                        "images": [
                            { "url": "dog/firstdog.jpeg" },
                            { "url": "dog/seconddog.jpg" },
                            { "url": "dog/thirddog.jpg" },
                            { "url": "dog/fourthdog.jpg" }
                        ]
                    },

                ]
}
var totalValues = ["cats","dogs"];
var imageArray = imageslide.therapy
function compare(imageArray,totalValues ){
    for(var i=0;i<imageArray.length;i++){
        for(var j=0;j<totalValues.length;j++){
            if(totalValues[j]=imageArray[i].name){
                console.log(imageArray[i].name+"=="+totalValues[j]);
                //imageArray[i].images.push({"url": "https://hexasoft.io"});
                //break;
                return imageArray[i].images;
            }
        }

    }
    //printResult(imageArray);
    return [];
}
function printResult(resultArray){
    for(var i=0;i<resultArray.length;i++) {
        console.log(resultArray[i].name);
        for(var j=0;j<resultArray[i].images.length;j++){
            console.log(resultArray[i].images[j]);
        }
    }
}
images = compare(imageArray, totalValues);
if(images.length > 0){
     for(var i=0;i<images.length; i++){
         images[i].push({"url": "your url"});
     }  
}

Answer №2

Explore the capabilities of the JavaScript filter function by checking out the documentation (Link).

If you need to filter images based on an animal name, you can use a similar approach:

function retrieveAnimalImagesByName(animal_name){
  var imageArray = imageslide.animalGallery;
  
  var filteredImages = imageArray.filter(animalData => {
    return animalData.name === animal_name;
  })
  return filteredImages[0].images;
}

Answer №3

If you want to give it a shot, here's a method that will provide URLs for each item in the totalValues array.

var totalValues = ["dogs"];
var videos = videoclip.soothing;

function retrieve(videos, totalValues ){
  let result;
  for( value of totalValues ) {
    for( thisVid of videos ) {
      if( thisVid.title == value ){
        result = thisVid.links;
      }
    }
  }
  
  return result;
}

Answer №4

If you're looking to generate a flat array of image URLs called pics, you can achieve that with the code below:

const pics = [].concat(...imageslide.therapy.map(element => {
  if (totalValues.indexOf(element.name) > -1) 
    return element.images.map(img => img.url)
}))
console.log(pics);

Answer №5

function checkImages(imageSet, valueList) {
    for (var x = 0; x < imageSet.length; x++) {
        for (var y = 0; y < valueList.length; y++) {
            if (valueList[y] == imageSet[x].title) {
                selectedImages.push(imageSet[x].urls);
                for (var i = 0; i < selectedImages.length; i++) {
                   for(var j = 0; j < selectedImages[i].length; j++){
                    displayImage(selectedImages[i][j].link);
                }
                }
            }
        }
    }
    showSelectedImages(current_index);
}

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

Invoking res.download() in the Express framework

It's puzzling why this issue is occurring, and it's quite frustrating. I was expecting the file to be downloaded in line with the guidelines provided in the Express documentation. Below is the code snippet I am using: //within React (App.js) ...

Error installing npm: Dependencies could not be loaded for installation

Currently, I am in the process of learning Angular JS by building a simple phonecat app. Following the steps, I have downloaded Node.js and attempted to execute the command: npm install An error has occurred: C:>npm install npm ERR! install Couldn&ap ...

What methods can be used to verify that a modal jquery dialog does not have focus anymore?

Does anyone know how to close a dialog box when clicking outside of it using either jQuery or plain JavaScript? I've heard suggestions about using the blur event, but it doesn't seem to work with jQuery dialogs. EDITI have the same question but ...

Dynamic field validation using jQuery

I am currently developing a wizard feature that retrieves employees dynamically from the backend. The employee table is created with a radio input field and then inserted into my HTML code: $.ajax({ method: "get", url: '/fetchEmployees/' ...

Updating the state of an object nested within another object in React JS

So, I have a nested object within another object and I need to update the state of one or more properties in the inner object. This is my current state: const [products, setProducts] = useState({ name: '', type: '', price: '& ...

Placing the overview right beneath the navigation bar in Bootstrap

I would like to create a large image similar to this: Just a big picture with oversized letters on it. I'm new to this, so please bear with me. Also, could someone guide me on how to achieve those big letters? It would be even more helpful if someone ...

A design with three columns that stretch to 100% height using CSS styling

I can't seem to figure out the CSS for this layout. Here is the HTML code I have: <body> <div id="main"> <div id="left"> menu </div> <div id="middle"> </div> ...

Incorporate the user's input text into the paragraph

Is there a way to dynamically insert user input text into a pre-existing paragraph? For instance: Enter Your Name: Alice Would be transformed into <p>Hello, my name is Alice</p> I am looking for a solution that can work on the same HTML pag ...

What is the best way to access and compare the values within each <td> element?

, my code looks like this: <table id="table_append"> <tr class='text-center'>" + <td>1</td> <td class="codeverify">025</td> <td> Data1 </td> </tr> ...

Ensure that the left menu remains fixed at full page height of 100%

I'm currently working on developing a website layout that includes a left menu bar and right content section, both of which are independently scrollable. However, I'm encountering a few challenges: The left menu bar doesn't cover the enti ...

Error: When attempting to send a message in a different channel, an undefined property 'send' is encountered causing a TypeError

I'm utterly stumped as to why I keep encountering this issue, so perhaps someone here can shed some light on it. The error message reads: TypeError: Cannot read property 'send' of undefined Here is the snippet of code in question: client.o ...

Why isn't the Vue component refreshing its view after the state changes in Vuex?

Recently, I delved into the world of vue and learned about its redux counterpart vuex. However, I'm facing an issue where changes in the vuex state are not triggering reactive updates to the view in a vue component. export const store = new Vuex.Store ...

The parameter type 'Function' cannot be assigned to the parameter type 'ComponentType<never>'

Having an issue passing a component to the connect method from react-redux. The error message I'm receiving is as follows: Argument of type 'Function' is not assignable to parameter of type 'ComponentType'. Type 'Function&ap ...

Discover the process of connecting a REST controller with AngularJS and Spring

I have a list of file paths stored in an array within the scope variable of an AngularJS Controller. My goal is to properly map these file paths to a Java REST controller for further processing. When I pass it as "/ABC/Scope-Variable," it successfully ma ...

Assign a custom value to the ng-options and ensure that the first option is selected by default

Hey there, I'm currently working on the following: $scope.test = [ {"value" : 0, "text" : "00:00"}, {"value" : 900, "text" : "00:15"}, {"value" : 1800, "text" : "00:30"} ]; and in my select element, this is what I hav ...

Align text vertically above and below an input field labeled using tailwindcss

I am striving to achieve the desired outcome but with the text in front of the input vertically aligned with the text after the input. https://i.sstatic.net/0WTfk.png Here is what I have created so far to accomplish that: <div class="space-x-2 fl ...

The NPM package manager is unable to locate jquery.js and jquery.keyframes.js

I've encountered an issue while working with jquery and jquery.keyframes. My project structure involves storing NPM js files in the node_modules folder and html files in the public folder. However, when I use the following code, the html file is unabl ...

JavaScript problem with hovering action causing additional buttons to appear

Currently, I am developing a user interface where, upon hovering over an LI element, 2 buttons appear to provide additional functionality - "edit" and "remove". However, I am facing challenges with the mouse hit zones. The mouseover function works effect ...

tips for choosing a specific dropdown menu item

I'm having an issue with a function that I want to apply to all my dropdown lists. The problem arises when I try to select an option from the second dropdown list - instead of displaying the correct value, it shows the value from the first group in th ...

The width of mat-table columns remains static even with the presence of an Input field

I'm currently working on an Angular component that serves the dual purpose of displaying data and receiving data. To achieve this, I created a mat-table with input form fields and used {{element.value}} for regular data display. Each column in the tab ...