2

I have an object which has a set of numbers

> var size = d3.values(data[0]);

>size
output:
["0", "14.71", "50.0", "35.29"]

>typeof(size);
output:
"object"

I want to sum up the width and get an output like below:

[0, 14.71, 64.71, 100]

But the output which I got is as below:

>var width = [size[0],
                    size[0]+size[1],
                    size[0]+size[1]+size[2],
                    size[0]+size[1]+size[2]+size[3]];

>width
output:
["0", "014.71", "014.7150.0", "014.7150.035.29"]

Please help me fix this. Thanks in advance...

1 Answer 1

11

You could use Array#map and thisArgs and an implicit casting to number for the element.

var data = ["0", "14.71", "50.0", "35.29"],
    width = data.map(function (a) {
        return this.count += +a;
    }, { count: 0});

console.log(width);

ES6 without use of thisArg (this would not work with an arrow function), but with a closure of count.

var data = ["0", "14.71", "50.0", "35.29"],
    width = data.map((count => a => count += +a)(0));

console.log(width);

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

6 Comments

Wow! Array seem to be your special friend :)
@NinaScholz Since the question is pretty straightforward, the real Wow goes to your use of the second argument of .map() to introduce an interim counter variable. That's a nice idea to avoid cluttering the outer scope with yet another variable! I am definitely going to resort to this for future applications.
@altocumulus, it's just a pattern to overcome the this problem (as temp variable) with arrow functions.
@NinaScholz I was talking about explicitly specifying the this argument within the call to .map() just for the sake of keeping track of the count in your ES5 snippet. This pattern may be so obvious to you that you won't find it worth mentioning, but it never occured to me to use it like this. Nicely done!
you could use, in this case data.map((count => a => +(count += +a).toFixed(2))(0));.
|

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.