1

I have 3 arrays. I want to loop through arr1 and then compare that each object in arr1 contains objects of arr2 and arr3 with chai assertion. The following is what I have tried and it failed

const arr1=[{name="Alice"},{name="Bob"}]
const arr2=[{name="Alice"}]
const arr3=[{name="Bob"}]
for (let i = 0, len = arr1.length; i < len; i++) {
    expect(arr1[i]).to.deep.equal(arr2|| arr3);
}
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Analyst
  • 105
  • 1
  • 9

2 Answers2

1

One easy way is to concatenate the 2 arrays in a temporary array and go ahead with your loop:

const arr4 = [...arr2, ...arr3];
for (let i = 0, len = arr1.length; i < len; i++) {
  expect(arr1[i]).to.deep.equal(arr4[i]);
}
Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
  • Thanks Silviu for the answer but the problem is the order of objects changes everytime so when comparing it failed as object at index[0] in arr4 does not match with arr1 – Analyst Oct 31 '22 at 12:48
  • @Analyst you need to clarify a few test cases so we know how to help you. Are you looking to compare arr1 with the first available element in arr2 or arr3? e.g. arr1 = [ "Alice", "Charlie", Daniel", "Bob" ]; arr2 = [ "Alice", "Bob" ]; arr3 = [ "Charlie", "Daniel" ]; Do you expect the test to pass or fail for this input? One quick fix would be to merge the arrays, e.g. arr4 in the original answer, sort arr1 and arr4 and compare one by one, like the above. You can also do it without sorting, e.g. https://stackoverflow.com/questions/71946433/check-if-an-array-is-a-merge-of-2-arrays – Silviu Burcea Nov 01 '22 at 05:21
  • Thanks Silviu, I was trying to compare objects and this is why test was failing. I make the changes and it is working now. – Analyst Nov 02 '22 at 13:14
  • @Analyst great! If my answer (or other) helped you, consider accepting it. – Silviu Burcea Nov 03 '22 at 05:47
0

Here's a possibility building on Silviu's answer. Use the array .find() function to look for possible matches in arr1 that match objects in the merged arrays.

If all objects of arr1 are found in the others, then test is green, else test fails. The following snippet passes for me, however if i was to add {name: "Charlie"} to arr1, we'll then see it start to fail.

test("Check value in array matches any value in other array", () => {
    const arr1=[{name:"Alice"},{name:"Bob"}]
    const arr2=[{name:"Alice"}]
    const arr3=[{name:"Bob"}]

    const merged = [...arr2, ...arr3]
    checkValuesExistInChildArray(arr1, merged)
})

const checkValuesExistInChildArray = (arr1, otherArrays) => {
    arr1.find(o => {
        const match = otherArrays.find(otherObject => otherObject.name === o.name)
        expect(match).exist
    })
}
SChristie
  • 171
  • 6