Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting distinct values from a JSON

I have my JSON as follows

{"DATA": [{"id":11,"name":"ajax","subject":"OR","mark":63}, {"id":12,"name":"javascript","subject":"OR","mark":63}, {"id":13,"name":"jquery","subject":"OR","mark":63}, {"id":14,"name":"ajax","subject":"OR","mark":63}, {"id":15,"name":"jquery","subject":"OR","mark":63}, {"id":16,"name":"ajax","subject":"OR","mark":63}, {"id":20,"name":"ajax","subject":"OR","mark":63}],"COUNT":"120"} 

Is there any good method to find out the distinct name from this JSON

Result javascript,jquery,ajax

I can do this using following methode

var arr=['']; var j=0; for (var i = 0; i < varjson.DATA.length; i++) {   if($.inArray(varjson.DATA[i]["name"],arr)<0){       arr[j]=varjson.DATA[i]["name"];       j++;   } } 

Is there any better method which gave me better performance?

like image 366
Nithesh Narayanan Avatar asked Jul 22 '13 05:07

Nithesh Narayanan


People also ask

Can JSON have multiple values?

JSON array can store multiple values. It can store string, number, boolean or object in JSON array. In JSON array, values must be separated by comma.

What is JSON format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).


1 Answers

I would use one Object and one Array, if you want to save some cycle:

var lookup = {}; var items = json.DATA; var result = [];  for (var item, i = 0; item = items[i++];) {   var name = item.name;    if (!(name in lookup)) {     lookup[name] = 1;     result.push(name);   } } 

In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.

Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.

like image 123
ZER0 Avatar answered Sep 23 '22 17:09

ZER0