0

I have a small requirement where in i need to remove the duplicate values from the array that i am getting.

Overview
In the below code, what i am trying to do is to get top 1000 employee names(Should Cost Modeler People Picker Field) through REST API from List A and appending those values in LIST B Drop down. But as i get all the names through REST API there are many duplicate values in the array.

What i would like to do is to remove the duplicate values and then append the values to drop down.

//Get the employee names

function getAllEmployeeNames(){
var results;
$.ajax({
    url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Should Cost Projects')/items?$select=Should_x0020_Cost_x0020_Modeler/Title&$expand=Should_x0020_Cost_x0020_Modeler/Id&$top=500",
    type: "GET",
    async:false,
    headers: {
        "Accept": "application/json;odata=verbose",
    },
    success: function (data) {
        if(data.d.results.length>0){
            results=data.d.results;
        }
    },
    error: function (data) {
    //alert("Error");
    }
});
return results;
  }

// To Append the Employee Name to drop down on form load.

var employeeName=$("input[title^='Employee Name']").val();
$("input[title^='Employee Name']").hide();
$("input[title^='Employee Name']").after("<select id='EmployeeField' class='ms-RadioText'><option value=''></option></select>");
$("input[title^='Project Name']").hide();
$("input[title^='Project Name']").after("<select id='ProjectField' class='ms-RadioText'><option value=''></option></select>");
var allEmployeeNames=getAllEmployeeNames();
console.log(allEmployeeNames);


    $.each(allEmployeeNames,function(i,employee){
    $.each(employee.Should_x0020_Cost_x0020_Modeler.results,function(j,item){
        if(employeeName==item.Title){
            $("#EmployeeField").append("<option selected='selected' value='"+item.Title+"'>"+item.Title+"</option>");
        }else{
            if(item.Title!=undefined){
                $("#EmployeeField").append("<option value='"+item.Title+"'>"+item.Title+"</option>");
            }           
        }   
    });         
});

// the code that i am using to remove duplicates but it is not working.

$(allEmployeeNames).each(function() {
    $(this).siblings('[value="'+ $(this).val() +'"]').remove();
});


Please help me solve this problem.
Thanks

  • What is the result you are getting? How can you use $(this) on looping an array of objects (result from SharePoint REST)? – harshal gite Oct 24 '18 at 13:18
  • Please try solution given in here as answer. Don't forget to use $top as query option. stackoverflow.com/questions/25744763/… – Hardik Dec 18 '18 at 12:21
0

What you can do is, find the unique values after getting results from your first REST call(After getting all possible employee names).

Then find the unique employees in your array and after getting unique values, append to dropdown. There are many ways to find the unique values in your array:

  1. Using Plain Javascript.
  2. Using JQuery.
  3. Using plugins like lodash.js or underscore.js

You can find more details to get unique values from your array, here.

  • I get what you are trying to say but i cannot do it that is why i have posted a question here – jayant khushalani Oct 25 '18 at 5:02
0

I see you have employee details in an arrays inside the results you get from SharePoint REST. For your case, you need to create a temporary array which will store the unique values of employee name. Check the code below:

var tempEmployeesArray = [];  

$.each(allEmployeeNames,function(i,employee){
  $.each(employee.Should_x0020_Cost_x0020_Modeler.results,function(j,item){
            if(employeeName==item.Title){
                if(tempEmployeesArray.indexOf(item.Title) < 0){
                    //code if duplicate not found
                    tempEmployeesArray.push(item.Title);
                    $("#EmployeeField").append("<option selected='selected' value='"+item.Title+"'>"+item.Title+"</option>");
                }

            }else{
                if(item.Title!=undefined){
                    if(tempEmployeesArray.indexOf(item.Title) < 0){
                        //code if duplicate not found
                        tempEmployeesArray.push(item.Title);
                        $("#EmployeeField").append("<option value='"+item.Title+"'>"+item.Title+"</option>");     
                }                        
                }           
            }   
        });
  • Hi I Tired your code above, it is not fetching all the names in the array it is fetching only 6 names – jayant khushalani Oct 25 '18 at 5:16
  • Which array are you talking about? – harshal gite Oct 25 '18 at 5:49
  • Can you explain why you have used 2 loops here? – harshal gite Oct 25 '18 at 5:49
  • The problem that i am facing is when i use top =1500 there are more than 5 arrays, i get the first array values how do i get all the array values? – jayant khushalani Oct 25 '18 at 9:28
  • 1
    Is this "Should_x0020_Cost_x0020_Modeler" people picker field is allowing multiple selections?? – Ganesh Sanap Oct 25 '18 at 9:47
0

You incorrectly use your jquery ajax function getAllEmployeeNames. You shouldn't use async: false for the modern web. Correct one:

function getAllEmployeeNames() {
    return $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Should Cost Projects')/items?$select=Should_x0020_Cost_x0020_Modeler/Title&$expand=Should_x0020_Cost_x0020_Modeler/Id&$top=500",
        type: "GET",
        headers: {
            "Accept": "application/json;odata=verbose",
        }
    })
    .then(function(data){
        return data.d.results;
    })
    .fail(function(err){
        console.log(err);
        alert('error');
    });
}

then you can filter unique names using array (that one option):

getAllEmployeeNames()
    .then(function(results){
        var uniqueNames = [];

        results.forEach(function(employee){
            employee.Should_x0020_Cost_x0020_Modeler.results.forEach(function(name){
                if(uniqueNames.indexOf(name) === -1) {
                    uniqueNames.push(name)
                }
            })
        })

        // now you have array with unique names
        // add it to dropdown here
    })
  • The problem that i am facing is when i use top =1500 there are more than 5 arrays, i get the first array values how do i get all the array values? – jayant khushalani Oct 25 '18 at 9:28
0

Using the code below to remove the duplicates options of the dropdown list.

$("#EmployeeField option").each(function() {
        $(this).siblings('[value="'+ $(this).val() +'"]').remove();
});
  • This is not working. As i am fetching 5000 top employee name, it does not remove the duplicate. – jayant khushalani Oct 25 '18 at 5:02
  • Could you help me regarding this – jayant khushalani Oct 25 '18 at 5:50
  • The problem that i am facing is when i use top =1500 there are more than 5 arrays, i get the first array values how do i get all the array values? – jayant khushalani Oct 25 '18 at 9:28
0

Replace this part of code

$(allEmployeeNames).each(function() {
    $(this).siblings('[value="'+ $(this).val() +'"]').remove();
});

with

var uniqueEmployeeNames = [];
$(allEmployeeNames).each(employee.Should_x0020_Cost_x0020_Modeler.results, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueEmployeeNames.push(el);
});
0

May be below code will help you

First of all get all data and bind it to drop-down list as you can see below

This is HTML for reference

<div>
    <select id="ddlEmployee">
        <option value="0">select user</option>
    </select>
</div>

Below is Js Code

 function getDataREST(requestUrl, successFun, failFun){
   $.ajax({
      url: requestUrl,
      type: "GET",
      async:false,
      headers: {
          "Accept": "application/json;odata=verbose",
      },
      success: function (data) {
          successFun(data)
      },
      error: function (data) {
         failFun(data)
      }
   });
}
function bindEmployeetoDDL(){
    var addItemUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('UserLists')/items?$select=Id, Title,UserName/Id,UserName/Title&$expand=UserName&$top=2000" 
    getDataREST(addItemUrl, function (data){
        if(data && data.d.results.length > 0)
        {
            for(i=0;i<data.d.results.length;i++){
                 $("#ddlEmployee").append("<option value='"+data.d.results[i].UserName.Id+"'>"+data.d.results[i].UserName.Title+"</option>");
            }
            //removeDuplicateByValue()
            removeDuplicateByText()
        }
    }, function (error){
        console.log("Error while getting employee", Error)
    });
}

After successfully data bind to drop-down one of below method to remove duplicate entry from drop-down options

//This will be remove duplicate options by value
function removeDuplicateByValue()
{
    $("#ddlEmployee Option").each(function() {
        $(this).siblings('[value="'+ $(this).val() +'"]').remove();
    });
}

//This will be remove duplicate options by text
function removeDuplicateByText()
{
    $("#ddlEmployee Option").each(function() {
        $(this).siblings(':contains('+ $(this).text() +')').remove();
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.