Bazinga777
Bazinga777

Reputation: 5291

Adding multiple strings as numbers in Javascript

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

Answers (4)

Microfed
Microfed

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

guest271314
guest271314

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

Peter Roehlen
Peter Roehlen

Reputation: 128

A few things you can do.

  1. Small fix to improve readability would be to assign the chan property to a variable so you don't have to repeat the whole path. E.g. var chan = result.channels.electricity.chan
  2. Use forEach to iterate over the array elements and increment a variable inside the loop.

Upvotes: 0

MinusFour
MinusFour

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

Related Questions