Returns the sum of numeric values in a JavaScript object

This technical problem deals with writing a function in JavaScript that returns the sum of all numeric values in an object. An example input and output are provided in the problem statement.

Problem

Given a JavaScript object, write a function that returns the sum of all the numeric values in the object.
Example input:
var obj = {
    a: 1,
    b: 2,
    c: "three"
};
Example output:
3

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:

var obj = {
    a: 1,
    b: 2,
    c: "three"
};

function sumNumericValues(obj) {
    var sum = 0;
    for (var key in obj) {
        if (typeof obj[key] === "number") {
            sum += obj[key];
        }
    }
    return sum;
}

sumNumericValues(obj);

// Explanation:

// This solution is optimal because it uses a for-in loop to iterate through the object.
// It then checks if the value is a number and if it is, it adds it to the sum.
// This solution is optimal because it is simple and easy to understand.

A.I. Evaluation of the Solution

This solution is a good solution that demonstrates a level of completeness and solves the problem. The approach is simple and easy to understand, which is good.

Evaluated at: 2022-11-20 10:16:39