Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Multidimensional Array remove Duplicates

I want to remove duplicates in my array with jQuery

The array

[[["Time",0],["Budget",1],["Scope",2],["Technical",3],["Budget",1]]]

If there is a name ("Budget") in this example which appears several times, then I want to remove this value pair.

I tried a lot but nothing worked so far. I tried to iterate trough the array and set a duplicate variable and just add the items with no duplicates to a new array

  var items       = new Array ();
// get the data with ajax request
 $.ajax({
                url : "localhost/..",
                dataType : 'json',
                success: function(data) {

for (var prop_name in data.items) {
                    var duplicate = 0;
                    var count = 0;

// count how often the value appears
for (i = 0; i < data.items.length; i++) {
                    if (data.items[prop_name] == data.items[i]){
                        var count = count+1               
                        }
                }
// if there are duplicates, just add the value once
for (i = 0; i < items.length; i++) {    
                if (data.items[prop_name] == data.items[i]){
                duplicate = duplicate+1;
                    }
                if (duplicate <= 1){
                        items.push([ data.items[prop_name], count]) 
                    }
                duplicate = 0;
            }
}
like image 328
simplesystems Avatar asked Sep 02 '26 14:09

simplesystems


1 Answers

Take a look at the following example. You can not use indexOf or $.inArray directly.

$ar=[["Time",0],["Budget",1],["Scope",2],["Technical",3],["Budget",1]];
$finalAr = [];
for($i=0;$i<$ar.length;$i++){
	$currentPair = $ar[$i];
  $pos = null;
  for($j=0;$j<$finalAr.length;$j++){
  	if($finalAr[$j][0] == $currentPair[0] &&$finalAr[$j][1] == $currentPair[1]){
    	$pos = $j;
    }
  }
  if($pos == null){
  	$finalAr.push($currentPair);
  }
}
for($i=0;$i<$finalAr.length;$i++){
  $("#result").append($finalAr[$i][0]+"-->"+$finalAr[$i][1]+"<br/>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
like image 163
arsho Avatar answered Sep 05 '26 04:09

arsho