0

I am working on a pre-BootCamp problem. I am taking an object and removing any properties that have odd numeric values, and then returning the object. Why are the odd values not being filtered out?

/*
Write a function called "removeOddValues".

Given an object, "removeOddValues" removes any properties whose valuse are odd numbers.

var obj = {
  a: 2,
  b: 3,
  c: 4
};
removeOddValues(obj);
console.log(obj); // --> { a: 2, c: 4 }
*/

function removeOddValues(obj) {
  for (var values in obj) {
      if (obj[values] === 'Number' && obj[values] % 2 !== 0) {
           delete obj[values]
      }  
      }   
      return obj;
};


var obj = {
  a: 2,
  b: 3,
  c: 4
};


removeOddValues(obj);

output:
{a: 2, b: 3, c: 4}

2 Answers2

3

They are not being removed since the If-statement you constructed doesn't evaluate to true for the conditions you have.

I think you are missing a typeof in the first condition. Your if-statement should read as follows:

if ((typeof obj[values]) === 'number' && obj[values] % 2 !== 0) ...

With that fixed, your code runs just fine:

function removeOddValues(obj) {
  for (var values in obj) {
    if ((typeof obj[values]) === 'number' && obj[values] % 2 !== 0) {
      delete obj[values]
    }
  }
  return obj;
};


var obj = {
  a: 2,
  b: 3,
  c: 4
};


console.log(removeOddValues(obj))
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
0

Just use this:

function removeOddValues(obj) {
  for (var values in obj) {
      if (typeof obj[values] === 'number' && obj[values] % 2 !== 0) 
           delete obj[values]           
  }   
  return obj;
};
michaelitoh
  • 2,317
  • 14
  • 26