I have a following array of maps
let input = [
{"name":"apple", "type":"fruit", "color": "red"},
{"name":"apple", "type":"fruit", "color": "green"},
{"name":"tomato", "type":"fruit", "color": "red", "taste":"sweet"},
{"name":"tomato", "type":"fruit", "color": "green", "taste":"sour"}
];
How do I check if there are two elements in this array - one containing red apples and green tomatoes?
I tried this:
console.log (
input.some(
(subMap) => subMap.name == "tomato" && subMap.color == "green")
&&
input.some(
(subMap) => subMap.name == "apple" && subMap.color == "red"));
For the above array, this returns true.
Looking for a more concise way of checking this.
Something like
input =[
{"name":"apple", "type":"fruit", "color": "red"},
{"name":"apple", "type":"fruit", "color": "green"},
{"name":"tomato", "type":"fruit", "color": "red", "taste":"sweet"},
{"name":"tomato", "type":"fruit", "color": "green", "taste":"sour"}
];
subArray = [{"name" : "apple", "color":"red"} , {"name":"tomato", "color" : "green"}]
//This function should return true
(input.hasElementsMatching(subArray)) => true
Thanks in advance
So, for each object in the subArray you need to find an item in the input which contains all the keys/values of that
object
function arrayContainsObjects(array, check) {
return check.every((objectToCheck) => {
return array.some((item) => {
return Object.entries(objectToCheck).every(
([key, value]) => item[key] === value
);
});
});
}
const input = [{
"name": "apple",
"type": "fruit",
"color": "red"
},
{
"name": "apple",
"type": "fruit",
"color": "green"
},
{
"name": "tomato",
"type": "fruit",
"color": "red",
"taste": "sweet"
},
{
"name": "tomato",
"type": "fruit",
"color": "green",
"taste": "sour"
}
];
const subArray = [{
"name": "apple",
"color": "red"
}, {
"name": "tomato",
"color": "green"
}];
console.log( arrayContainsObjects(input,subArray) );