nsayer
nsayer

Reputation: 829

Search for all values in array of objects

I have three arrays.

One of them contains values I will be testing. The two others are arrays of object which might include the values of my first array under the name key.

const myArray = ["foo", "bar"];

const testArray1 = [
    {name: "foo"},
    {name: "bar"},
    {name: "something else"}
]

const testArray2 = [
    {name: "foo"},
    {name: "rab"},
    {name: "something else"}
]

I am trying to write a condition which would return true only if the tested array contains all of the values of my first array.

With the same example it would give me something like this :

if (testArray1.containsAll(myArray)) // true
if (testArray2.containsAll(myArray)) // false

What is the best way to resolve this ?

Thanks, any help much appreciated

Upvotes: 1

Views: 92

Answers (3)

Mustafa Dal
Mustafa Dal

Reputation: 21

can be use, every and some. these are return only true/false

const myArray = ["foo", "bar"];

const testArray1 = [
    {name: "foo"},
    {name: "bar"},
    {name: "something else"}
]

const testArray2 = [
    {name: "foo"},
    {name: "rab"},
    {name: "something else"}
]

let result1 = testArray1.every(item => myArray.some(array => item.name == array))
let result2 = testArray2.every(item => myArray.some(array => item.name == array))

console.log('result1', result1)
console.log('result2', result2)

Upvotes: 2

Ishwar Patil
Ishwar Patil

Reputation: 1736

Check this out. May not be the best way but works perfectly fine.

const myArray = ["foo", "bar"];

const testArray1 = [
    {name: "foo"},
    {name: "bar"},
    {name: "something else"}
]

const testArray2 = [
    {name: "foo"},
    {name: "rab"},
    {name: "something else"}
]
let aFlag = testArray1.filter( a =>  myArray.includes(a.name)).length === myArray.length;
let bFlag = testArray2.filter( a =>  myArray.includes(a.name)).length === myArray.length;
console.log(aFlag, bFlag)

Upvotes: 1

Faly
Faly

Reputation: 13356

With array.prototype.every and array.prototype.find, it should be:

const myArray = ["foo", "bar"];

const testArray1 = [
    {name: "foo"},
    {name: "bar"},
    {name: "something else"}
];

const testArray2 = [
    {name: "foo"},
    {name: "rab"},
    {name: "something"}
];

console.log(myArray.every(s => testArray1.find(o => o.name === s)));
console.log(myArray.every(s => testArray2.find(o => o.name === s)));

Upvotes: 2

Related Questions