0

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?

1
  • 2
    numerous ways to wrap a loop around this Commented Jan 23, 2016 at 18:31

4 Answers 4

3

With reduce is pretty simple:

var sum = results.channels.electricity.chan.reduce(function(a, b){
    return a + Number(b.day[0]._);
}, 0);
Sign up to request clarification or add additional context in comments.

Comments

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)

3 Comments

Thanks, but my data structure doesn't allow me to use this.
@Bazinga777 "my data structure doesn't allow me to use this" Can describe why data structure does not allow approach ? Is data structure an array ?
I am parsing an xml file parsed to json which looks pretty bad, so this would create a bit of a mess
1

Just for fun. With some ES6-7 features:

let chans = results.channels.electricity.chan;
let total = chans.reduce((sum, { day: [ { _ } ] }) => (sum + Number(_)), 0);

Comments

0

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.

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.