Search code examples
javascriptarraysunderscore.js

Pattern Matching in javascript returning true if first array has 2 and second array has 22 How do i solve this?


I have two arrays one of it is having user id and another one is having user ids. Those arrays are as follows.

1)The array which is having user id. data[key].effective_employees Which is eaqual to [2].

Now I have another array which is having numbers of employee ids which is as follows. data2[0].id Which is eaqual to [2,22,21].

And now I am trying to see whether the array two has number in array 1 I am using the following logic to see whether it is working or not.

if ((/^\d+$/.test(_.intersection([data2[0].id.toString()], data[key].effective_employees)))) {
    let isElem = _.contains(returnStackFilterd, value);
    if (isElem == false) {
        returnStackFilterd.push(value);
    }
} else {
    returnStackFilterd = _.without(returnStackFilterd, value);
}

But this is showing true for the number 2 if the array two is having 22. Psudo code of what is happening with it is as follows.

if([2]is in[22,21]){ it is printing true} I want false here as the number two is not in the second array. The second array contains 22 and 21 which is not eaqual to 2

How do i solve this problem? The above psudo code should print false.


Solution

  • If data[key].effective_employees is the number 2, and data2[0].id is the array [2, 22, 21], the expression to test whether data2[0].id contains data[key].effective_employees is:

    data2[0].id.includes(data[key].effective_employees)
    

    From your original question, data2[0].id.toString() coerces the array to a string 2,22,21, which is no use to you. You also do not need to use Underscore for this.