1

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.

1

2 Answers 2

2

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

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

Comments

1

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);
});

2 Comments

This is exactly the suggestion I would give, make sure you mark this as the correct answer if it solved your problem. =)
@Jans: Great to hear, you can accept my answer if indeed it helped you :)

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.