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
CodePudding user response:
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);
CodePudding user response:
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);
