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}
0

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Luca! You are right, I was missing 'typeof.'
And the type of a Number is "number", not "Number" ;-)
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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.