-3

I'm trying to check for an if condition iteratively inside a for loop. That means some expressions of if conditions need to be generated iteratively as shown in the below example

let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []
for(let i=0; i<union.length; i++){
  if(union[i] % 2 == 0 && union[i] !== control[i]){
    result.push(union[i])
  }
}

In the above example union[i] !== control[i] is the conditional expression that need to be validated/generated iteratively. In words we can state the problem as

result array should contain only even numbers from the union array and it should not contain any element from the control array

So the result array should be [8]

Lalas M
  • 1,116
  • 1
  • 12
  • 29

4 Answers4

1

result array should contain only even numbers from the union array and it should not contain any element from the control array

let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []

union.forEach(item => {
    if(item % 2 == 0 && !control.includes(item)) {
        result.push(item);
    }
});

The .includes method checks if the item is in the array.

or just a simple filter

const result = union.filter(item => item % 2 == 0 && !control.includes(item));
Michael Mano
  • 3,339
  • 2
  • 14
  • 35
0

Use Array#filter with a Set.

The problem with your code is for every item in union you need to check every item in control, whether it exists or not, which you are not doing.

And I would recommend using a Set instead of searching in an array repeatedly.

const 
  union = [1, 2, 3, 4, 5, 6, 7, 8, 9],
  control = [2, 4, 6],
  result = ((s) => union.filter((u) => !(u&1) && !s.has(u)))(new Set(control));
console.log(result);
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

1 more option. remove duplicate item between 2 arrays then just check for even numbers.

let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []

union = union.filter(function(val) {
  return control.indexOf(val) == -1;
});

for(let i=0; i<union.length; i++){
  if(union[i] % 2 == 0){
    result.push(union[i])
  }
}
0

You can modify the check and see if control.includes(union[i]). This will be true when control includes the current union variable. This is also true for the other way round, meaning if control includes the union variable, the union variable also contains the control variable. Negate the check with ! to see if it doesn't include this value.

let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []
for(let i=0; i<union.length; i++){
  if(union[i] % 2 == 0 && !control.includes(union[i])){
    result.push(union[i])
  }
}
console.log(result);
cloned
  • 6,346
  • 4
  • 26
  • 38