0

I have a list of objects, where each object has numerical values:

var cpuInfo = [
  { user: 189625143,
    nice: 0,
    sys: 40239022,
    idle: 2087123838,
    irq: 720490 },
  { user: 76627160,
    nice: 0,
    sys: 35444113,
    idle: 2204916386,
    irq: 18233303 }
]

I need to calculate the value of idle divided by the sum of all values.

For that, I need to get the sum of all of the values in all of the objects.

I've tried doing this to extract just the values:

_(cpuInfo).each(_.values)

I expected it to return a list like so:

[189625143, 0, 40239022, 2087123838, 720490, 76627160, 0, 35444113, 2204916386, 18233303]

But for some reason it returns the exact same thing I started out with - a list of objects. Even if I expand it to this:

_(cpuInfo).each(function(item) { return _(item).values() })

It still returns just the list of objects.

What am I doing wrong?

2 Answers 2

4
var res = _.map(cpuInfo, function (el) {
  return _.values(el)  
})
res = _.flatten(res)

console.log(res);

Demo: http://jsbin.com/rodipu/1/edit?js,console

Sign up to request clarification or add additional context in comments.

Comments

2

In pure JavaScript

temp = [];
cpuInfo.forEach(function(obj){
    Object.keys(obj).forEach(function(k){
        temp.push(obj[k]);
    });
});

Ref - Object.keys(), Array.prototype.forEach()

Note - both functions compatible with >IE8

Comments

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.