Reputation: 5162
I have a JSON dataset like the following
var data=
[
{"id":10,"marks":20},
{"id":20,"marks":30},
{"id":10,"marks":40},
{"id":10,"marks":60},
{"id":10,"marks":70}
]
I want to get keep only rows with unique ids. That means i should have data with following rows only
[
{"id":10,"marks":20},
{"id":20,"marks":30}
]
In real thi size of the file is huge. And I want to show the average mark of unique ids. For making average I am using a different code. So that i am adding a different column at reading the json file. i.e.
{"id":10,"marks":20,"avg":25}
So i want to keep the rows with unique ids only otherwise in the visualization the avg is coming multiple times for the same id. How can i do that easily in d3.js? Or is there any good option?
Upvotes: 0
Views: 84
Reputation: 21578
There are obviously many ways of getting an array of unique objects. As far as I am aware, there is no built-in mechanism in d3 providing this functionality. I have always done it by having an associative array to keep track of objects which are already present in the output array. Adjusted to your needs it would be something like:
var contains = {},
unique = [];
for (var i = 0; i < data.length; i++) {
if(!contains[data[i].id]) {
contains[data[i].id] = true;
unique.push(data[i]);
}
}
See this JSFiddle.
Upvotes: 1