1

i have this array:

    var res =
[
  { '5': 0 },  { '23': 0 },
  { '74': 0 }, { '45': 0 },
  { '10': 0 }, { '46': 1 },
  { '33': 0 }, { '18': 0 },
  { '67': 1 }, { '28': 0 },
  { '68': 0 }, { '56': 0 },
  { '78': 0 }, { '71': 0 },
  { '50': 1 }, { '14': 0 },
  { '39': 0 }, { '91': 0 },
  { '37': 0 }, { '34': 0 }
];

I want to sum second values to get result. like in this example result must be 2. I am using nodejs, if it helps.

Thank you.

3
  • 2
    I would probably first go back to the code that generated this data and put it in a more convenient way to process. An object with unknown keys is usually a sign that there's a better way to store and therefore process this data. Commented Dec 24, 2020 at 22:15
  • And, what should your sum do if an object has more than one property in it? Commented Dec 24, 2020 at 22:16
  • As a hint Object.values(obj)[0] will get you the "first" value in an object where "first" is in quotes because if there's more than one value, it's not clear what your algorithm wants to do. Commented Dec 24, 2020 at 22:17

1 Answer 1

1

You could use Object.values to extract the value for each such object and then sum them. Using map and reduce, this can even be done in a one liner:

const total =  res.map(o => Object.values(o)[0]).reduce((a, b) => a + b, 0);
Sign up to request clarification or add additional context in comments.

1 Comment

@Corvus actually, the conversion to number is redundant - I didn't notice you already had number literals there. I've edited my answer to remove it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.