0

I am trying to get multiple index positions on an Array for a Boolean value.

I have tried applying a loop using while and for to iterate more then one index position with no success so far.

Here is my code:

let jo = [1,2,3,4,5]
let ji = [1,2,3]

let checker = (arr1,arr2) => {

  let falsy = arr1.every(num => arr2.includes(num)) == false ? 
    arr1.map(falsy => arr2.includes(falsy)) : "tba";

  //the block below is the frustrated attempt:

  let i = falsy.indexOf(false);
  while(i>=0){
    return falsy.findIndex(ih => ih == false)
  }

}

console.log(checker(jo,ji))

I would like to get the index where false occurs stored in a variable that has iterated over all array so I can use this variable to return just the false values on falsy like this:

return falsy[i] = [4,5]

Then after that I will add more to the first if statement to check both arr1 x arr2 or arr2 x arr1

Thanks in advance!

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Arp
  • 979
  • 2
  • 13
  • 30
  • 5
    Can you take a step back and clarify what you're trying to achieve? You've described your *attempt* but not so much the problem that you're attempting to solve; *"I am trying to get multiple index positions on an Array for a Boolean value."* is not very descriptive. Given your two arrays, what should the result be and *why*? – Tyler Roper Oct 29 '19 at 16:42
  • Is this for trying to find the [symmetric difference of arrays](https://stackoverflow.com/a/33034768/)? – VLAZ Oct 29 '19 at 17:23

1 Answers1

0

It looks like you're attempting to get the difference between two arrays. This is a fairly comment use-case for Sets. In this case, your code would look like this:

let jo = [1,2,3,4,5]
let ji = [1,2,3]

const checker = (arr1, arr2) => {
    return new Set(arr1.filter(x => !new Set(arr2).has(x)))
}

console.log(checker(jo, ji));  // {4, 5}

If you wanted to get the indexes of the differences, you would need to apply a map to the result of the new Set like so:

const checker = (arr1, arr2) => {
    const difference = new Set(arr1.filter(x => !new Set(arr2).has(x)));
    return Array.from(difference).map(value => arr1.indexOf(v));
}
Daniel Samuels
  • 423
  • 7
  • 25
  • thanks so much for your reply. I am studying JS and I still did not know Set() method. When I input the first block of code, that should bring the diff in between arrays I am getting the following: ```console.log(checker(jo, ji))``` returns ```:[object Set]``` . Why is that? Shouldn´t it return ```{4,5}```? And also, how could I get an array instead of an object as a return? Thanks very much, sir! – Arp Oct 30 '19 at 11:42
  • An output of `[object Set]` would usually be a result of you logging the `String()` representation of the object, rather than the object itself. To get an array instead of a `Set` you can use `Array.from(set_variable)` – Daniel Samuels Oct 30 '19 at 11:54