0

I have a simple array problem: I have two different arrays: one with strings and one with objects. I need to check one agains the other in a certain way: Array of objects needs to check if a property of the object is included in array of strings, and return a response in 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}] 

My expected response array would be something like:

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

I don't know how to tackle this, as I've tried several things with no success. I tried double iterations, but it gave me a wrong response. I've also tried the method includes, but then I can only check my objColors array, therefore I don't get a response for all the cases I need to check

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

Could someone please give me a hint on how to check them to get the desired response? Thanks in advance

0

2 Answers 2

1

First turn the array of objects into a structure that's easier to check through - perhaps a Map, or a Set of the values that are true. Then you can map the colors array and look up the associated value.

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer! It works but most importantly, it prompted me to watch some videos on the Set property and learn a little more, so thank you very much
1

An approach with an object.

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);

1 Comment

Thanks! I was not familiar with the fromEntries method and I found it very practical as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.