简体   繁体   English

使用visualforce组件从阵列中删除重复项

[英]Removing duplicates from array using on visualforce component

I want to remove duplicates from final array showing on my visualforce page . 我想从显示在我的visualforce页面上的最终数组中删除重复项。

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 更新了原始代码

Your code works, you just forgot to remove the data.results = result line, that prevent you from getting the correct result: 您的代码有效,您只是忘记删除data.results = 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 : 您还可以使用reduce方法

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

See fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM