Justice Nelson
Justice Nelson

Reputation: 15

What is wrong with my if condition

I found the answer to this question on this site but i just want to understand why my solution wasn't working. The question asked to implement an difference function, which subtracts one list from another.

It should remove all values from list a, which are present in list b.

My Original Code :

function array_diff(array,num) {
  var results = [];

  array.forEach(function(ele, idx, array){
    if (num !== ele) {
      results.push(ele)
      console.log("a is now " + ele)
      console.log("b is " + num)
    } 
  })
  return results;
} 

But everytime i feed it this argument array_diff([1,2,2],[2]), it returned the original array and i dont know why

Upvotes: 1

Views: 81

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

You are using an array for num instead of a number.

array_diff([1, 2, 2], 2)
//                    ^

function array_diff(array, num) {
    var results = [];

    array.forEach(function(ele, idx, array){
        if (num !== ele) {
            results.push(ele);
            console.log("a is now " + ele);
            console.log("b is " + num);
        } 
    });
    return results;
} 

console.log(array_diff([1, 2, 2], 2));

If the question is about using an array for numbers, then you could use Array#indexOf to check if the element is in the numbers array. You could use Array#filter as well.

function array_diff(array, numbers) {
    return array.filter(function(element) {
        return numbers.indexOf(element) === -1;
    });
} 

console.log(array_diff([1, 2, 2], [2]));
console.log(array_diff([1, 2, 2, 3, 4, 5, 6, 6, 6, 7], [1, 3, 5, 7]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

kkesley
kkesley

Reputation: 3406

You compared it with an array (num) which will always return false since your ele is an integer.

use this instead

array_diff([1,2,2], 2)

or if you want to change the function

function array_diff(array,num) {
  var results = [];

  array.forEach(function(ele, idx, array){
    if (num.indexOf(ele) === -1) {
      results.push(ele)
      console.log("a is now " + ele)
      console.log("b is " + num)
    } 
  })
  return results;
} 

Upvotes: 1

Pierre Glandon
Pierre Glandon

Reputation: 5

Your comparaison is wrong, you should write :

if(num != ele)

and not

if(num !== ele)

Upvotes: -1

Related Questions