1
\$\begingroup\$

What could be the shortest code for filtering the following array in Javascript without any library?

My code is:

filtered_obj = _.where(obj, { name: "Alpha" });

This uses a JS library called underscore.

Test case:

objs = [{'id':1,'name':'Alpha'},{'id':2,'name':'Beta'},
{'id':3,'name':'Gamma'},{'id':4,'name':'Eta'},
{'id':5,'name':'Alpha'},{'id':6,'name':'Zeta'},
{'id':7,'name':'Beta'},{'id':8,'name':'Theta'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}];

filtered_obj =[{'id':1,'name':'Alpha'},{'id':5,'name':'Alpha'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}]
\$\endgroup\$
6
  • 1
    \$\begingroup\$ @closevoter: Questions asking tips about golfing code are on-topic. \$\endgroup\$
    – Leaky Nun
    Jul 18, 2016 at 6:49
  • 2
    \$\begingroup\$ @LeakyNun It sure is, but without some proof of actual research from the OP, we can't say if it only is a genuine tips question or a do-my-homework one. Might be why someone closevoted \$\endgroup\$
    – Katenkyo
    Jul 18, 2016 at 6:49
  • \$\begingroup\$ I used underscore which is filtered_obj = _.where(obj, { name: "Alpha" }); then I am looking for not using any library. \$\endgroup\$ Jul 18, 2016 at 6:54
  • 2
    \$\begingroup\$ I'm voting to close this question as off-topic because I agree with @Katenkyo and think this is a homework question in disguise. \$\endgroup\$
    – Blue
    Jul 18, 2016 at 7:51
  • \$\begingroup\$ @muddyfish Go ahead. Appreciate the help anyways. \$\endgroup\$ Jul 18, 2016 at 7:54

1 Answer 1

1
\$\begingroup\$

45 bytes

filtered_obj=objs.filter(n=>n.name=='Alpha');

This uses the filter function for arrays.

Ideone it!

\$\endgroup\$
4
  • \$\begingroup\$ please look into it ideone.com/p3cENn \$\endgroup\$ Jul 18, 2016 at 6:51
  • \$\begingroup\$ Because I'm using spidermonkey instead of rhino. \$\endgroup\$
    – Leaky Nun
    Jul 18, 2016 at 7:02
  • \$\begingroup\$ How did you calculate the number of bytes for the solution as 45 bytes? \$\endgroup\$ Jul 18, 2016 at 7:07
  • 1
    \$\begingroup\$ by counting the number of characters in filtered_obj=objs.filter(n=>n.name=='Alpha');. \$\endgroup\$
    – Leaky Nun
    Jul 18, 2016 at 7:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.