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;
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With