在javascript中从数组中删除重复的数组值

Remove duplicate array value from array in javascript

本文关键字:数组 删除 javascript      更新时间:2023-09-26

我想从我的数组中删除重复的条目,而我的数组是

        ArrayTotal All Banks,Total All Banks,Total Domestic Banks,Total Domestic Banks,B2B Bank,B2B Bank,Bank of Montreal,Bank of Montreal,The Bank of Nova Scotia,The Bank of Nova Scotia,

我们想删除重复的条目,我正在php unique_array中尝试,我也在javascript 中尝试

      var uniqueNames = [];
      $.each(names, function(i, el){
      if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
      });
     console.log(uniqueNames) its gave error Unexpected token A

尝试php、

$dup=array();
foreach($bname as $k=>$v) {
if( ($kt=array_search($v,$bname))!==false and $k!=$kt )
 { unset($unique[$kt]);  $dup[]=$v; }
}

这样尝试此处演示

var names = ["Total All Banks","Total All Banks","Total Domestic Banks","Total Domestic Banks","B2B Bank","B2B Bank","Bank of Montreal","Bank of Montreal","The Bank of Nova Scotia","The Bank of Nova Scotia"];
var uniqueNames = [];
$.each(names, function(i, el){
    if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});
console.log(uniqueNames);

您应该能够使用array_unique在PHP中实现这一点,如下所示:

// Your existing array
$items = [ "Total All Banks", "Total All Banks", "Total Domestic Banks", "Total Domestic Banks", "B2B Bank", "B2B Bank", "Bank of Montreal", "Bank of Montreal", "The Bank of Nova Scotia", "The Bank of Nova Scotia" ];
// array_unique does the dirty work for you
$noduplicates = array_unique($items);
// results are in $noduplicates
print_r($noduplicates);

这里是在PHP中,没有array_unique:

// Your existing array
$items = [ "Total All Banks", "Total All Banks", "Total Domestic Banks", "Total Domestic Banks", "B2B Bank", "B2B Bank", "Bank of Montreal", "Bank of Montreal", "The Bank of Nova Scotia", "The Bank of Nova Scotia" ];
// Our new array for items 
$noduplicates = [];
// Loop through all items in an array
foreach($items as $item) {
    // Check new array to see if it's there
    if(!in_array($item, $noduplicates)) {
        // It's not, so add it
        $noduplicates[] = $item;
    }
}
// results are in $noduplicates
print_r($noduplicates);

这里是用Javascript编写的-您不需要使用jQuery来完成此任务:

// Your existing array
var items = [ "Total All Banks", "Total All Banks", "Total Domestic Banks", "Total Domestic Banks", "B2B Bank", "B2B Bank", "Bank of Montreal", "Bank of Montreal", "The Bank of Nova Scotia", "The Bank of Nova Scotia" ];
// Our new array for items
var noduplicates = []; 
// Loop through all items in an array
for (var i = 0; i < items.length; i++) {
    // Check new array to see if it's already there
    if(noduplicates.indexOf(items[i]) == -1) {
        // add to the new array
        noduplicates.push(items[i]);
    }
}
// results are in noduplicates
console.log(noduplicates);

Fiddle在这里可用。