Removing duplicates from array using on visualforce component

I want to remove duplicates from final array showing on my visualforce page .

Actual Working code :(I am getting duplicates in array)

                function(result, event){

                     //if success
                    if(event.status){

                    var data = {results: []}
                    data.results = result;   
                    query.callback(data);             


                    }
                     else{
                          alert('Invalid Field/Object API Name : '+event.message);
                     }

                 }, 
                  {escape: true}
            );
        }  

Example Code I took for change :

function unique(list){
var result = [];
$.each(list, function(i, e) {
    if ($.inArray(e, result) == -1) result.push(e);
  });
  return result;
}

Work All Around for result :

     if(event.status){ 
     var result = [];
     var data = {results: []}
     $.each(list, function(i, e) {
     if ($.inArray(e, data.results) == -1)                    data.results.push(e);
   });
    data.results = result;                            
    query.callback( data);                           
    }

But i cant able to get result .Please help me to make this work.Please let me know if my question is unclear.

Updated original code

Answers


Your code works, you just forgot to remove the data.results = result line, that prevent you from getting the correct result:

var result = [];
var data = {results: []}

$.each(list, function(i, e) {
  if ($.inArray(e, data.results) == -1)
    data.results.push(e);
});

// You have to comment the following line, or data.result get reset
// You could also push to result instead of data.results
// in the $.each function above

//data.results = result;                            
// ...                           
console.log(data.results) // => data.results has unique elements!

You could also use the reduce method:

data.results = list.reduce(function(ar,item) {
  if(result.indexOf(item) == -1)
    ar.push(item)
  return ar
}, result)

See fiddle


Need Your Help

Parallel Uploading images to Azure blob what can be a better option?

c# parallel-processing message-queue azure-storage-blobs

i have a List and Every Message has a Image and List now i need to update the blob Url for Image and Attachment for Every Message