Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove any properties whose values are numbers greater than the given number

Tags:

javascript

:)

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!

like image 424
learninghowtocode Avatar asked Dec 24 '22 20:12

learninghowtocode


2 Answers

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);
like image 139
ibrahim mahrir Avatar answered Dec 31 '22 13:12

ibrahim mahrir


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);
like image 37
kind user Avatar answered Dec 31 '22 12:12

kind user