skip to Main Content

Please, help to undestand the problem? Can’t het result – total amount

const objectWithNumbers = {
  a: 10,
  b: 20,
  c: "string",
  d: 12,
};

function sumObjectValues(obj) {
  Object.values(obj).reduce((sum, key) => {
    if (typeof obj[key] === "number") {
      sum += obj[key];
    }
return sum
  }, 0);
}

const result = sumObjectValues(objectWithNumbers);
console.log(result);
//42should be 

Tried to use reduce and can’t get result

2

Answers


  1. few errors.

    1. you need to return the value from function
    2. Object.values actually gives the values not the keys
    const objectWithNumbers = {
      a: 10,
      b: 20,
      c: "string",
      d: 12,
    };
    
    function sumObjectValues(obj) {
      return Object.values(obj).reduce((sum, val) => {
        if (typeof val === "number") {
          sum += val
        }
    return sum
      }, 0);
    }
    
    const result = sumObjectValues(objectWithNumbers);
    console.log(result);
    //42should be 

    or you can use Object.keys

    const objectWithNumbers = {
      a: 10,
      b: 20,
      c: "string",
      d: 12,
    };
    
    function sumObjectValues(obj) {
      return Object.keys(obj).reduce((sum, key) => {
        if (typeof obj[key] === "number") {
          sum += obj[key];
        }
    return sum
      }, 0);
    }
    
    const result = sumObjectValues(objectWithNumbers);
    console.log(result);
    //42should be 
    Login or Signup to reply.
  2. An one-liner with a ternary operator:

    const objectWithNumbers = {
      a: 10,
      b: 20,
      c: "string",
      d: 12,
    };
    
    const sum = Object.values(objectWithNumbers).reduce((sum, val) => typeof val === 'number' ? sum + val : sum, 0);
    
    console.log(sum);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search