Jans
Jans

Reputation: 35

Reducing Javascript sub array to single array

I have a result of the following code

 d3.csv("../hello.csv", function(data) {
    console.log(data);
    var usable = data.map(function (d) {
        return {    
            description: d.description.split(" ")
        };
    });
    console.log(usable);
});

the console log of the usable is [object, object, object] when I expand it is

0:Object
  description: Array[3]
    0 : "A"
    1 : "B"
    2 : "C"

1:Object
  description: Array[3]
    0 : "D"
    1 : "E"
    2 : "FG"

2:Object
  description: Array[5]
    0 : "AD"
    1 : "BD"
    2 : "DC"
    4 : "HH"

What I need is single array as follows:

[A,B,C,D,E,FG,AD,BD,DC,HH]

with all elements reduced to single array rather than having multiple.

How can I achieve this? Any help would be highly appreciated.

Upvotes: 1

Views: 174

Answers (2)

Ezequiel Muns
Ezequiel Muns

Reputation: 7752

Why not:

d3.csv("../hello.csv", function(data) {
    console.log(data);
    var all = [];
    data.map(function (d) {
        Array.prototype.push.apply(all, d.description.split(" "));
    });
    console.log(all);
});

Upvotes: 1

helderdarocha
helderdarocha

Reputation: 23637

You can flatten the array using D3.merge(). Assume these are your objects:

var obj1 = {description: [1,2,3]}
var obj2 = {description: [10,20,30,40]};
var obj3 = {description: [100,200,300,400,500]};

var array = [obj1, obj2, obj3]; // your array

So this produces the output you described:

console.log("array", array);

You can use d3.merge(array) to merge several arrays into one:

var flattened = d3.merge([obj1.description, obj2.description, obj3.description]);
console.log("flattened", flattened);

It will print:

flattened [1, 2, 3, 10, 20, 30, 40, 100, 200, 300, 400, 500]

See: JSFiddle

Upvotes: 2

Related Questions