Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove repeated object values from arrayList Jquery/Javascript

I have an arrayList with objects in it. I need to show only one value, if objects has the same values.

For Example : [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ] From the above example I need to show only the first and second object and skip the third object because it is as same as first object.

Note : the objects in array can be infinite, I cant hardcode the index value. Can anyone help me out the generic solution.

This is what I have tried:

points = [];
newarr = [];
locArray = [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ];

if(abc!=null){
removeDuplicateCoordinates();
                        $.each(newarr,function(key,val){
                           points.push([val.a,val.b]);

                        });

}

function removeDuplicateCoordinates(){
                var arr = locArray;
                $.each(arr, function(index,item){
                    if(searchForItem(newarr,item)<0){
                        newarr.push(item);
                    }
                });
            }
            function searchForItem(array, item){
                var i, j, current;
                for(i = 0; i < array.length; ++i){
                    if(item.length === array[i].length){
                        current = array[i];
                        for(j = 0; j < item.length && item[j] === current[j]; ++j);
                        if(j === item.length)
                            return i;
                    }
                }
                return -1;
            }

2 Answers

Fiddle Demo
try this one

    newarr = [];
    testarr = [];
    locArray = [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ];
    for (var i = 0; i<locArray.length;i++)
        {
    var idx = $.inArray(String(locArray[i].a)+String(locArray[i].b), testarr);
    if (idx == -1) {
      testarr.push(String(locArray[i].a)+String(locArray[i].b));
      newarr.push(locArray[i]);
        }
     }
    console.log(newarr);
like image 131
SimarjeetSingh Panghlia Avatar answered Nov 21 '25 18:11

SimarjeetSingh Panghlia


One of my favorite methods:

usedArray = {};
locArray = [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ];
for (key in locArray) {
    if (usedArray[JSON.stringify(locArray[key])] == undefined) {
        console.log(JSON.stringify(locArray[key]));
        usedArray[JSON.stringify(locArray[key])] = true;
    }
}

Don't know anything about how fast it is, but it works for me everytime. Working fiddle.

instead of console.log(JSON.stringify(locArray[key])); You can populate new array:

newarr.push(locArray[key]);

EDIT

Test width 100000 objects in fiddle ~300ms i can live with that.

like image 38
Bogdan Kuštan Avatar answered Nov 21 '25 18:11

Bogdan Kuštan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!