Home > database >  How to use type of in objects to get oddValues
How to use type of in objects to get oddValues

Time:03-13

1.Here is the task.

 Declare a function removeOddValues.
  • @param {object} ??? - an object
  • @returns {object} a new object that contains the same key/value pairs as the given object, except that any key/value pair where the value is an ODD number is removed

2.Your code here.

  function removeOddValues(obj){
   let result = {};
   for(const key in obj){
    if(typeof obj[key] % 2 === 0){
     result[key] = obj[key];
     return result;
   }
   else if(!isNaN(obj[key]))
    return obj;
   }
 }

3.Here is the test.

test(removeOddValues({ a: 1, b: 2, c: 3 }), { b: 2 });
test(removeOddValues({ a: "1", b: "2", c: "3" }), {
a: "1",
b: "2",
c: "3",
});
// If a line gets really long, you can put key/value pairs on new lines.

4.Here is the error.

enter image description here

But output are supposed to be {b:2} and { a: "1", b: "2", c: "3" }, not both are { a: "1", b: "2", c: "3" }

CodePudding user response:

I think your problem is in the if check. You are checking if the typeof value is divisible by 2, it will return NaN since typeof obj[key] is returning string or number and modulus of that will be NaN. Your condition in else if passes so the whole object is being returned.

CodePudding user response:

Here is a more functional way of doing the same:

function removeOddValues(o){
 return Object.entries(o)
   .reduce((a,[k,v])=>{
     if (typeof v==="string" || v%2===0) a[k]=v;
     return a;
   }, {});
}

console.log(removeOddValues({ a: 1, b: 2, c: 3 }));
console.log(removeOddValues({ a: "1", b: "2", c: "3" }));

  • Related