Description:
Remove the Duplicate SharePoint List Items and bind the unique list items to dropdown -JSOM and CAML
CAML does not support duplicate data-remove. Below article described the filter the unique data by using CAML with the array.
Problem Description: List name called Countries. It has Title and State columns. Each county has different states so Country name does not repeat more than one time after binding to the drop-down.
Below 3 lines of code removed the duplicate data.
var duplicate = [];
- if (!duplicate[oListItem.get_item('Title')])
- {
- duplicate[oListItem.get_item('Title')] = true;
Full Implementation Steps:
Create list name Countries and create column names Title and State.
Edit the page and add script edit webpart. add below code in script edit webpart
Javascript References
- <script type="text/javascript" src="/_layouts/15/init.js"></script>
- <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
- <script type="text/javascript" src="/_layouts/15/sp.js"></script>
- <script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Write CAML query.
- getListItems();
- var Items = { ItemList: [] };
- function getListItems() {
- var clientContext = new SP.ClientContext.get_current();
- var oList = clientContext.get_web().get_lists().getByTitle('countries');
- var camlQuery = new SP.CamlQuery();
- camlQuery.set_viewXml('<View></View>');
- this.listItemCollection = oList.getItems(camlQuery);
- clientContext.load(listItemCollection);
- clientContext.executeQueryAsync(
- Function.createDelegate(this, this.onListDataLoadQuerySucceeded),
- Function.createDelegate(this, this.onListDataLoadQueryFailed));
- }
Filter :
- function onListDataLoadQuerySucceeded(sender, args)
- {
- var listItemInfo = '';
- var listItemEnumerator = listItemCollection.getEnumerator();
- var duplicate = [];
- while (listItemEnumerator.moveNext()) {
- var oListItem = listItemEnumerator.get_current();
- if (!duplicate[oListItem.get_item('Title')])
- {
- duplicate[oListItem.get_item('Title')] = true;
- var tempItem = { ID: oListItem.get_id(), Value: oListItem.get_item('Title') };
- Items.ItemList.push(tempItem);
- }
- }
- var ddlCountry = document.getElementById('ddlCountry');
- if (ddlCountry != null)
- {
- for (var i = 0; i < Items.ItemList.length; i++)
- {
- var ListOption = new Option;
- ListOption.value = Items.ItemList[i].ID;
- ListOption.text = Items.ItemList[i].Value;
- ddlCountry.options[i] = ListOption;
- }
- }
- }
- function onListDataLoadQueryFailed(sender, args)
- {
- alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
- }
Close </script> tag
Dropdown where need to bind the data.
- <select id="ddlCountry"></select>
Results:
Removed the Duplicate data and bind to the dropdown.
Note: Data not removed from the original list Countries. it filters and binds to the dropdown.