Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript object to array of numbers

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...

like image 812
Gil Baggio Avatar asked Apr 17 '26 12:04

Gil Baggio


1 Answers

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);
like image 55
Nina Scholz Avatar answered Apr 20 '26 03:04

Nina Scholz