0

I am trying to filter to get value by nested data so if my input is ... enter image description here

currently I use the code below to get b from maximum a for each name ( christine, smiths, aaron ) . But I am trying to get value b where a = 2 for each name ( christine, hannah, jeannie)

  var names = d3.nest()
      .key(function(d) { return d.name; })
      .entries(data);

   names.forEach(function(n) {
    n.maxAValue = d3.max(n.values, function(d) { return d.b; });
                             });

the above works fine, but I was trying to get value where a == 2 with something like this below. Is there a way I could do something like this in javascript ?

names.forEach(function(n) { n.values, 
       function(d) { if(d.a == 2) { return d.b; }  }
                          });

======Edit======

data = [
  {
    "name":"apple",
    "a":1,
    "b":"jame"
  },
  {
    "name":"apple",
    "a":2,
    "b":"christine"
  },
  {
    "name":"orange",
    "a":1,
    "b":"nick"
  },
  {
    "name":"orange",
    "a":2,
    "b":"hannah"
  },
  {
    "name":"orange",
    "a":3,
    "b":"smiths"
  },
  {
    "name":"peach ",
    "a":1,
    "b":"boo"
  },
  {
    "name":"peach ",
    "a":2,
    "b":"jeannie"
  },
  {
    "name":"peach ",
    "a":3,
    "b":"aaron"
  }
]
5
  • 1
    To filter data in any kind of way, I like to use lodash, it helps a lot with array manipulation. Commented Mar 9, 2015 at 19:59
  • @HuguesStefanski can you show me exactly how to do this in my case, i 'm fairly new to javascript. .. Commented Mar 9, 2015 at 20:02
  • Would you happpen to have your data in json format? Or maybe a plunk/jsbin already? Commented Mar 9, 2015 at 20:06
  • @HuguesStefanski just added data = json Commented Mar 9, 2015 at 20:15
  • 1
    Plnkr using lodash: plnkr.co/edit/PfgQjwAmbz4JxTyZBxaB?p=preview Commented Mar 9, 2015 at 20:21

1 Answer 1

3

You can use the built-in array.filter function for this:

var filtered = data.filter(function(d) {
   return d.a == 2; 
});

Here's a JSFiddle that demonstrates this in action and then uses d3 to bind the filtered data to an HTML ul:

http://jsfiddle.net/bywdq375/1/

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

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.