Distinct Values from SharePoint List using Client Object Model

In this blog it's explained that how can we get distinct values from SharePoint List using JavaScript Client Object model and JQuery.

Below is code example that can be used when you need to get Count of Distinct values in a Column of SharePoint list. The example is using JavaScript Client Object model and Jquery.

Lets look at the method getDistinctItemsFromList(). You need pass the “Listname” and specify “ColumnName” in the code.

function getDistinctItemsFromList(Listname) {

try {

var context = new SP.ClientContext.get_current();

var list = context.get_web().get_lists().getByTitle(Listname);

var items = list.getItems();

context.load(items);

context.executeQueryAsync(

function () {

var itemCount = items.get_count();

var itemsarry = new Array(parseInt(itemCount) – 1);

var ListEnumerator = items.getEnumerator();

//adding values to array

for (i = 0; i < itemCount; i++) {

itemsarry[i] = new Array(0);

itemsarry[i][0] = items.get_item(i).get_item(ColumnName);

}

//gettig count of unique values from array

var uniqueItemsCount = 0;

var uniqueItems = {};

$.each(itemsarry, function () {

var num = this[0];

uniqueItems[num] = uniqueItems[num] + 1 || 1;

uniqueItemsCount++;

});

//uniqueItems is your array with Column value and the associated Count.

//uniqueItemsCount is how many of these distinct values exist.

//Now to extract the values from this array use the snippet below

var j = 0;

$.each(uniqueItems, function (itemValue, noOfItems) {

if (itemValue != ‘undefined’);

{

alert(itemValue);

alert(noOfItems);

j++;

}

});

},

function (sender, args) { alert(“error in inner request: ” + args.get_message()); }

);

}

catch (e) { alert(“Please check the WebPart Properites and the values in the specified list. Error :”+ e); }

}