0

function removeNumbersLargerThan(num, obj) {
  for (var key in obj) {
    if (!isNaN(obj[key]) && obj[key] > num) {
      delete obj.key;
    }
  }
  return obj;
}
var obj = {
  a: 8,
  b: 2,
  c: 'montana'
}
removeNumbersLargerThan(5, obj);
console.log(obj); // Should be {b: 2, c: 'montana'}
The function should remove any property that meets the 'if' condition inside the 'for' loop, but it doesn't.
Elan
  • 539
  • 1
  • 6
  • 18
  • Being that everyone is giving you the same answer, but nobody is explaining *why* you need square brackets: In your example, the `key` variable is a *`string`*. If you want to use the `delete obj.key` notation, `key` must be the actual name of the key you want to delete. To delete a key by its name as a string, you need to do `delete obj["myKey"]`. – Tyler Roper Apr 25 '17 at 15:55

2 Answers2

3

You miss the square brackets, while defining the object key to delete.

function removeNumbersLargerThan(num, obj) {
  for (var key in obj) {
    if (!isNaN(obj[key]) && obj[key] > num) {
      delete obj[key];
    }
  }
  return obj;
}
var obj = {
  a: 8,
  b: 2,
  c: 'montana'
}
removeNumbersLargerThan(5, obj);
console.log(obj); // Should be {b: 2, c: 'montana'}
kind user
  • 40,029
  • 7
  • 67
  • 77
1

You should replace delete obj.key; with delete obj[key];

Alina Loi
  • 184
  • 6