JSON tips: filter objects from array of objects where object name is alpha

1

1

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'}]

Gupteshwari

Posted 2016-07-18T06:40:33.777

Reputation: 13

Question was closed 2016-07-18T10:59:16.733

1

@closevoter: Questions asking tips about golfing code are on-topic.

– Leaky Nun – 2016-07-18T06:49:17.400

2@LeakyNun It sure is, but without some proof of actual research from the OP, we can't say if it only is a genuine [tag:tips] question or a [tag:do-my-homework] one. Might be why someone closevoted – Katenkyo – 2016-07-18T06:49:43.000

I used underscore which is filtered_obj = _.where(obj, { name: "Alpha" }); then I am looking for not using any library. – Gupteshwari – 2016-07-18T06:54:02.507

2I'm voting to close this question as off-topic because I agree with @Katenkyo and think this is a homework question in disguise. – Blue – 2016-07-18T07:51:46.153

@muddyfish Go ahead. Appreciate the help anyways. – Gupteshwari – 2016-07-18T07:54:05.377

Not sure whether is homework or should be closed, but certainly I would expect a tip to be formulated in more generic style. – manatwork – 2016-07-18T09:43:16.853

Answers

1

45 bytes

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

This uses the filter function for arrays.

Ideone it!

Leaky Nun

Posted 2016-07-18T06:40:33.777

Reputation: 45 011

please look into it http://ideone.com/p3cENn

– Gupteshwari – 2016-07-18T06:51:34.977

Because I'm using spidermonkey instead of rhino. – Leaky Nun – 2016-07-18T07:02:45.180

How did you calculate the number of bytes for the solution as 45 bytes? – Gupteshwari – 2016-07-18T07:07:13.803

1by counting the number of characters in filtered_obj=objs.filter(n=>n.name=='Alpha');. – Leaky Nun – 2016-07-18T07:08:05.197