How can you get distinct values from a SharePoint List column using JavaScript without a huge performance hit?
A simple example would be appreciated :)
How can you get distinct values from a SharePoint List column using JavaScript without a huge performance hit?
A simple example would be appreciated :)
Assuming that your field is a Choice/MultiChoice field without "Fill In Choices" enabled then you can use get_choices.
If it does have fill in choices and/or is a different field type then I don't think there is an option apart from brute force (iter over all items getting unique values).
http://spdailytips.blogspot.com/2011/11/retrieve-all-choice-field-values-using.html
<script type="text/ecmascript">
function GetChoiceValues() {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
context.load();
// Get the list
var taskList = web.get_lists().getByTitle("list");
// Get Department choice field (choice field)
var deptChoiceField =
context.castTo(taskList.get_fields().getByInternalNameOrTitle("department"),
SP.FieldChoice);
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),
Function.createDelegate(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args) {
var choices = deptChoiceField.get_choices();
listBoxControl1.Items.Add(choices);
alert("Choices: (" + choices.length + ") - " + choices.join(", "));
}
function onFailureMethod(sender, args) {
alert("failed. Message:" + args.get_message());
}
</script>
I personally prefer /_vti_bin/listdata.svc. For example to retrieve only Title och Status from 100 first Tasks:
http://dev/_vti_bin/listdata.svc/Tasks()?$select=Title, StatusValue&top=100
See more on my blog: $select, $.getJSON and listdata.svc, updating with listdata.svc
I've written this function which will get unique values for a column in SharePoint Online, without having to iterate through each item.
function getUniqueColumnValues(listid, viewid, column, _callback){
var uniqueVals = [];
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_layouts/15/filter.aspx?ListId={" + listid + "}&FieldInternalName=" + column + "&ViewId={" + viewid + "}&FilterOnly=1&Filter=1",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
}).then(function(response) {
$(response).find('OPTION').each(function(a,b){
if ($(b)[0].value) {
uniqueVals.push($(b)[0].value);
}
});
_callback(true,uniqueVals);
},function(){
_callback(false,"Error retrieving unique column values");
});
}