Compare an array of strings with an array of objects and provide a specific result for each comparison

I'm facing a simple array dilemma: I have two separate arrays - one containing strings and the other containing objects. What I need to do is compare them in a specific manner: The array of objects should verify if a property of each object is present in the array of strings, and then provide a response for each case.

const colors = ["blue", "pink", "red", "green", "yellow", "orange", "white"]

const objColors = [{name:"pink", value: true}, {name:"green", value: true}, {name: "white", value: false}] 

The expected resulting array should look like this:

const res = [false, true, false, true, false, false, false]

I've been struggling to find a solution despite my various attempts. I experimented with double iterations which led to inaccurate results. Additionally, I attempted using the includes method but that only allowed me to check the objColors array, leaving some cases unchecked.

let res = objects.map(x => (strings.includes(x.name)))

If anyone could offer me some guidance on how to approach this problem to achieve the desired outcome, I would greatly appreciate it. Thank you in advance.

Answer №1

To simplify the process, first transform the array of objects into a more manageable structure such as a Map or a Set containing only the true values. Then, iterate through the colors array and retrieve the corresponding value from the transformed structure.

const colors = ["blue", "pink", "red", "green", "yellow", "orange", "white"];
const objColors = [{name:"pink", value: true}, {name:"green", value: true}, {name: "white", value: false}];


const trueColors = new Set(
  objColors
    .filter(({ value }) => value)
    .map(({ name }) => name)
);
const res = colors.map(color => trueColors.has(color));
console.log(res);

Answer №2

Using an object-based approach.

const
    colors = ["blue", "pink", "red", "green", "yellow", "orange", "white"],
    objColors = [{ name: "pink", value: true }, { name: "green", value: true }, { name: "white", value: false }],
    wanted = Object.fromEntries(objColors.map(({ name, value }) => [name, value])),
    result = colors.map(c => !!wanted[c]);

console.log(result);

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

Retrieve Wikipedia API JSON information using jQuery

$('#searchButton').click(function(){ var searchInput = ""; searchInput = document.getElementById('test'); if(searchInput.value !== ""){ $.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format ...

Express and Mongoose error handling improvements for updates and puts

I'm new to using Express and I need help with my code for updating a model in my router/controller. I want to update certain parameters without modifying the "create_date" parameter, but I keep encountering an error. updateFood = function(req, res){ ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

The command 'node' is not being recognized as either an internal or external command, potentially due to it being an operable program or batch file. This issue only arises when attempting to

Whenever I try to npm install a package or check the node/npm version, it works fine. However, upon attempting to start the app with any scripts, I encounter the following error message. [EDITED] $ npm start > <a href="/cdn-cgi/l/email-protection" ...

Determine the prior location of an element using jQuery

Is there a way to track the previous location of an element before it is appended? I have 50 elements that need to be appended to different targets based on a certain condition. How can I determine where each element was located before being moved? $(&a ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Steps to avoid the button being submitted twice

I am facing an issue with two buttons in my code. One button is used to increase a count and the other button is meant to submit the count and move to the next page. The problem is that when I click on the "Proceed" button, it requires two clicks to procee ...

Encasing a drop-down menu within a personalized container

I am looking to create a custom HTML element that mimics the behavior of the native <select> element but also triggers a specific update function whenever an attribute or child node is modified. This is essential for incorporating the bootstrap-selec ...

Error: The connection to Node/Postgresql was refused at 127.0.0.1:5432. This occurred after connecting at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)

After running a Node server connecting to a Postgresql DB (via Knex) without issues, my laptop crashed. Upon restart, the DB connection stopped working, showing this error message: Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect ...

Can you show me the method to retrieve the value of client.query in Node JS using PG?

I have been working with node.js to establish a database connection with postgresql. Here is what my dbConfig.js file looks like: var pg = require('pg'); var client = new pg.Client({ host:'myhoost', port:'5432', ...

Understanding how to display a component within another component in Vue.js

I am faced with a scenario where I have a component that has the following template: <div v-for:"item in store" v-bind:key="item.type"> <a>{{item.type}}</a> </div> Additionally, I have another component named 'StoreCompone ...

Introduce a pause for each individual element when looping through an array

I'm attempting to utilize an SKLabelNode to sequentially display the elements from the array below on the label. It seems that the issue lies in the fact that the array iteration occurs faster than the sequence can complete, leading to a crash because ...

Utilizing ThreeJS: Implementing a Sprite in Conjunction with the OculusRiftEffect

I am currently working on a project for the OculusRift using the OculusRiftEffect found at https://github.com/mrdoob/three.js/blob/master/examples/js/effects/OculusRiftEffect.js and incorporating Sprites into the design. However, I am facing an issue where ...

Problem encountered with imaskJS in handling the formatting of data with forward slashes

After conducting tests on the frontend of the imask website at , it has been verified that utilizing a forward slash for date formatting results in the exclusion of the final digit of the date. Various attempts were made, including: IMask( field, ...

Adjust top position dynamically during resizing

When resizing the window, I am facing an issue with the image going outside of the box. I believe adjusting the position top of the image based on the box height might help in fitting the image properly within the box. $(window).resize(function() { va ...

I encountered a problem while trying to incorporate the solution that prompts another button click event

Interesting topic: JQuery / JavaScript - triggering button click event from another button <input type="submit" name="savebutton" id="uniqueOne" /> <input type="submit" name="savebutton" id="uniqueTwo" /> I have implemented a feature on my si ...

executing jQuery toggle on freshly generated content

I have a webpage that I designed using jQuery. Within this page, there is a table with rows assigned specific color classnames (e.g., tr class="yellowclass"). Users can filter the rows by clicking checkboxes to show/hide tables of different colors. The i ...

Developing components with jQuery

I have a JavaScript program that works perfectly when I use the following line of code: li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>"); However, if I change the above line ...

Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method. Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080 Here is an image of the console showing ...

Exploring JSON Object Iteration Using jQuery for AJAX Requests in JavaScript

I am struggling to grasp this concept. Currently, I have a JSON file that contains a collection of hospitals, including their addresses, operating hours, and phone numbers. My goal is to make an AJAX call to retrieve data from the JSON file and display i ...