Reputation: 5291
I have the following piece of code that converts multiple strings into number, which works fine, but I don't like the way it looks and want to know if I could write it in a better way.
Number(result.channels.electricity.chan[0].day[0]._)
+ Number(result.channels.electricity.chan[1].day[0]._)
+ Number(result.channels.electricity.chan[2].day[0]._)
+ Number(result.channels.electricity.chan[3].day[0]._)
+ Number(result.channels.electricity.chan[4].day[0]._)
+ Number(result.channels.electricity.chan[5].day[0]._)
Is there a cleaner way of writing this?
Upvotes: 0
Views: 922
Reputation: 2890
Just for fun. With some ES6-7 features:
let chans = results.channels.electricity.chan;
let total = chans.reduce((sum, { day: [ { _ } ] }) => (sum + Number(_)), 0);
Upvotes: 1
Reputation: 1
Try using while
loop
var channels = ["1", "2", "3", "4", "5"], i = -1, res = 0;
while (++i < channels.length ) res += Number(channels[i]);
console.log(res)
Upvotes: 1
Reputation: 128
A few things you can do.
var chan = result.channels.electricity.chan
Upvotes: 0
Reputation: 14423
With reduce is pretty simple:
var sum = results.channels.electricity.chan.reduce(function(a, b){
return a + Number(b.day[0]._);
}, 0);
Upvotes: 3