4

:)

I need to remove properties whose values are numbers greater than the given number. I've looked at this question: How do I remove a property from a JavaScript object? and this one: Remove some properties from array of javascript objects and this one: remove item from array javascript but I still cannot seem to get the desired answer I need. (They're either returning the numbers only or other parts of the array I don't need.)

This is the code I wrote:

 function removeNumbersLargerThan(num, obj) {
arr = [];
for (var i = 0; i < obj.length; i++) {
return arr[i] > 5;
}
}
var obj = {
  a: 8,
  b: 2,
  c: 'montana'
};
removeNumbersLargerThan(5, obj);

This is my result:

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

The correct console.log should be this though:

   { b: 2, c: 'montana' }

Any advice? Thank you! PS: I'm new and my questions seem to be getting marked down a lot even though I'm trying to follow the rules. If I'm posting incorrectly could someone please let me know what I'm doing wrong if they're going to mark me down? This way I can improve. I'm here to learn! :D Thanks so much!

Community
  • 1
  • 1

4 Answers4

5

function removeNumbersLargerThan(num, obj) {
  for (var key in obj) {                    // for each key in the object
    if(!isNaN(obj[key]) && obj[key] > num)  // if the value of that key is not a NaN (is a number) and if that number is greater than num
      delete obj[key];                      // then delete the key-value from the object
  }
}

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

removeNumbersLargerThan(5, obj);

console.log(obj);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
3

Object.keys() function returns all the keys of given object as an array. Then, iterate over them and check if specified key is bigger than given number, if so - delete it.

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

function clean(obj, num){
  Object.keys(obj).forEach(v => obj[v] > num ? delete obj[v] : v);
  console.log(obj);
}

clean(obj, 5);
kind user
  • 40,029
  • 7
  • 67
  • 77
2

javascript at Question does not check object property value. you can use Object.entries() to get an array of property key, value pairs, for..of loop to iterate properties and values, delete property of object if value is equal to or greater than 5

function removeNumbersLargerThan(num, obj) {
  for (let [key, value] of Object.entries(obj)) {
    if (typeof value === "number" && value > 5) delete obj[key]
  }
}
guest271314
  • 1
  • 15
  • 104
  • 177
0
function removeNumbersLargerThan(num, obj) {

  for(const property in obj){ 
    if(obj[property] > num){
      delete obj[property];   
    }
  }   
   console.log(obj)
}

/*

1. compare the numbers  
2. delete what you need to    
3. RETURN your needs


You can check MDN for for...in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

*/

heyfranksmile
  • 169
  • 1
  • 5