0

Write a function called "removeNumbersLargerThan".

Given a number and an object, "removeNumbersLargerThan" removes any properties whose values are numbers greater than the given number.

var obj = {
  a: 8,
  b: 2,
  c: 'montana'
}

removeNumbersLargerThan(5, obj);

console.log(obj); // --> { b: 2, c: 'montana' }

my code:

function removeNumbersLargerThan(num, obj) {
  // your code here
  if (obj[prop] < num) {
    delete obj[prop];
  }
}

What's wrong with my code? I'm not sure how to get rid of a property from an object if the property isn't defined?

msanford
  • 11,803
  • 11
  • 66
  • 93
Shirley
  • 31
  • 3
  • 8
  • 3
    I think you and [this poster](http://stackoverflow.com/questions/43615295/iterative-conditional-removal-of-object-property-using-for-in-and-if) are using the same text book... – Tyler Roper Apr 26 '17 at 20:23
  • 1
    *Larger* than. You're doing less than. `<` should be `>`. And you need to iterate over the properties. Read up on `for...in` loops. – Mike Cluck Apr 26 '17 at 20:23
  • 1
    @Santi Ack! Good catch. – msanford Apr 26 '17 at 20:24
  • 1
    *"What's wrong with my code?"* The most obvious mistake is that `prop` is not defined anywhere. Where do you expect it to come from? – Felix Kling Apr 26 '17 at 20:26

1 Answers1

2

Firstly, you're trying to remove numbers that are smaller than a given number. You can fix this by using property > num instead of property < num.

Next, you're not actually looking at all of the properties. Infact, prop is undefined. You need to use a for loop to check each property.

var obj = {
  a: 8,
  b: 2,
  c: 'montana'
}

removeNumbersLargerThan(5, obj); console.log(obj); // --> { b: 2, c: 'montana' }

function removeNumbersLargerThan(num, obj) {
    for (var property in obj) {
        if (obj[property] > num) {
            delete obj[property];
        }
    }
}
Toby Mellor
  • 8,093
  • 8
  • 34
  • 58