0

I am working on a D3.JS chart using an array named "dataset" where each entry is an object with a key and value attributes, such as the following:

dataset= 
 [
 {"key":"alpha", "value": [ {}, { } ...]},
 {"key":"beta", "value": [ { }, { } ...]},
 {"key":"gamma", "value": [ {}, { } ...]},
 {"key":"delta", "value": [ { }, { } ...]}
 ];

I need to extract one of those objects to create a new array. I have tried the following:

filteredDataset = dataset.filter(function(d){ console.log("d",d); if(d.key === "gamma") return d});

I can see in the console that I am accessing each object in the dataset, but the resulting filteredDataset comes out empty. What am I doing wrong?

2
  • 1
    I get [ { key: 'gamma', value: [ {}, {} ] } ] Commented Apr 10, 2014 at 5:14
  • Your code is correct. I tested it and there isn't any issues. Commented Apr 10, 2014 at 5:15

2 Answers 2

1

For clarity filter should be used by returning a boolean:

Like:

filteredDataset = dataset.filter(function(d){ return d.key === "gamma"})

And on my end the code

var dataset = [
     {"key":"alpha", "value": [ {}, { }]},
     {"key":"beta", "value": [ { }, { }]},
     {"key":"gamma", "value": [ {}, { }]},
     {"key":"delta", "value": [ { }, { }]}
]; 
filteredDataset = dataset.filter(function(d){ return d.key === "gamma"})

Outputs:

[ { key: 'gamma', value: [ {}, {} ] } ]

So please double check your code

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

2 Comments

Matyas and @thefoureye: For some reason, my code was giving me a null array as result of the filtered dataset. I did the changes that Matyas suggested and it works!!! Thanks, do you have any ideas why the code was not working for me in the first place?
Sorry but I don't have any ideas why the other way did not work. Because essentially you may return any object that evaluates to true, so your code should've been valid as well
0

dataset.filter(function(d){return d.key === 'gamma';});
This returns the data where key === gamma.

https://github.com/mbostock/d3/wiki/Selections#filter

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.