Find unique object in array depending on passed object key
Find unique object in array depending on passed object key
by schlomm
JavaScript
//test array
var selectProjects = [{
"target": "url",
"idProperty": 109,
"description": "Testlauf",
"email": "mail",
"simulation_Id": 109,
"project": "project",
"timestamp": "2017-07-10T07:14:00.000Z",
"title": "title",
"username": "user",
"simulation_unit": "100m",
"id": 454,
"simulationGeometry": {
"type": "polygon",
"rings": [
[
[0,0],
[0,0],
[0,0],
[0,0],
[0,0]
]
],
"_ring": 0,
"spatialReference": {
"wkid": 25832,
"latestWkid": 25832
}
}
}, {
"target": "url",
"idProperty": 112,
"description": "Test",
"email": "mail",
"simulation_Id": 112,
"project": "project",
"timestamp": "2017-07-11T10:39:00.000Z",
"title": "Test",
"username": "user",
"simulation_unit": "100m",
"id": 457,
"simulationGeometry": {
"type": "polygon",
"rings": [
[
[0,0],
[0,0],
[0,0],
[0,0],
[0,0]
]
],
"_ring": 0,
"spatialReference": {
"wkid": 25832,
"latestWkid": 25832
}
}
}]
//create prototype function used in next prototype function
Array.prototype.contains = function(v) {
for (var i = 0; i < this.length; i++) {
if (this[i] === v) return true;
}
return false;
};
//create prototype function to get unbique values depending on passed key
Array.prototype.unique = function(key) {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (!arr.contains(this[i][key])) {
arr.push(this[i][key]);
}
}
return arr;
}
var uniques = JSON.stringify(selectProjects.unique("simulation_unit"));
alert(uniques)