unique-values
grab the unique values for a field
by ryanttb
HTML
<label for="source" class="json">Source data</label>
<textarea id="source" name="source"></textarea>
<label><span>uniquify</span> <input type="text" id="a1" value="" /></label>
<button type="button">GO!</button>
<label for="dest" class="json">Output</label>
<textarea id="dest" name="dest"></textarea>
CSS
button, label {
display: block;
}
label span {
display: inline-block;
width: 12em;
}
textarea {
width: 80%;
height: 10em;
}
JavaScript
$("button").click(function() {
$("#dest").val("");
var source;
var item;
var args = {};
var allArgsValid = true;
$("input").each(function() {
if (!this.value) {
allArgsValid = false;
return false;
} else {
args[this.id] = this.value;
}
});
try {
source = JSON.parse($("#source").val());
} catch (e) { }
if (!source || !$.isArray(source)) {
$("#dest").val("source is not a JSON array");
} else if (!allArgsValid) {
$("#dest").val("all input and output fields are required");
} else {
var countryNames = [];
for (var i = 0; i < source.length; i++) {
item = source[i];
// do stuff with item
if ($.inArray(item[args.a1], countryNames) == -1) {
countryNames.push(item[args.a1]);
}
//countries[item[args.a1]] = true;
}
$("#dest").val(JSON.stringify(countryNames.sort()));
}
});