I'm trying to create an array in javascript with unique elements from a JSON feed. Maybe I think to much in php but there a simple script as below works.
$this = array();
foreach($array as $key => $value) {
if (!in_array($value,$this)) {
array_push($this,$value);
}
}
In JS it doesn't:
var this = new Array();
$.each(data, function(i,field) {
var value = field['needed'];
if (!$.inArray(value, this)) {
this.push(value);
}
}
It just adds every field['needed'] to this.
Full code so you know how I get my JSON
$(function() {
$("#wtf").empty();
$.getJSON("http://localhost/ahsmedia/openingsuren/api.php?first=" + cal.currentDate.format('d-m-Y'),
function(data) {
var camp = new Array();
$.each(data, function(i,field) {
var dt = field['datum'];
var ca = field['campus'];
var ca = ca.toLowerCase();
if ($.inArray(ca, camp)) {
camp.push(ca);
}
$("#wtf").append(field['campus'] + ' ' + cal.currentDate.format('d-m-Y') + ': ' + " " + field['open'] + "-" + field['close'] + " " + field['type'] + "<br />");
});
console.log(camp);
});
});
JSON looks like:
[
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Kantienberg",
"open": "08:00:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Kattenberg",
"open": "08:00:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Mariakerke",
"open": "08:30:00",
"close": "18:00:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Amandsberg",
"open": "09:30:00",
"close": "11:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Amandsberg",
"open": "12:00:00",
"close": "17:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Annaplein",
"open": "08:15:00",
"close": "12:30:00"
},
{
"datum": "2015-01-07",
"type": "normal",
"campus": "Sint-Annaplein",
"open": "13:30:00",
"close": "17:30:00"
}
]
I'm probably forgetting an important step before checking if the field is in the array, but I'm quite new to this, so I don't find it.
To be clear, I need an array with every unique campus like
['Kantienberg','Kattenberg','Mariakerke','Sint-Amandsberg','Sint-Annaplein']
but I get
["kantienberg", "kattenberg", "mariakerke", "sint-amandsberg", "sint-amandsberg", "sint-annaplein", "sint-annaplein"]
thisis a reserved keyword, you should not attach variables to itinArrayreturns-1if not found api.jquery.com/jquery.inarray. So it is still true. You have to check for>-1.