Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct value from the javascript array of object

I do have this kind of object

var j = [{'one':1},{'two':2},{'three':3},{'four':4},{'five':5},{'one':1}];

Now I want to skip the duplicate record. Can anyone suggest me the way?


1 Answers

A generic solution to filter out objects with multiple properties.

var list = [{'one':1},{'two':2},{'four':4},{'one':1},{'four':4},{'three':3},{'four':4},{'one':1},{'five':5},{'one':1}];


Array.prototype.uniqueObjects = function(){
    function compare(a, b){
        for(var prop in a){
            if(a[prop] != b[prop]){
                return false;
            }
        }
        return true;
    }
    return this.filter(function(item, index, list){
        for(var i=0; i<index;i++){
            if(compare(item,list[i])){
                return false;
            }
        }
        return true;
    });
}

var unique = list.uniqueObjects();

EDIT:

It won't be possible to compare first or second property as the properties of an object is not in order in javascript. What we can do is compare using property.

Array.prototype.uniqueObjects = function (props) {
    function compare(a, b) {
      var prop;
        if (props) {
            for (var j = 0; j < props.length; j++) {
              prop = props[j];
                if (a[prop] != b[prop]) {
                    return false;
                }
            }
        } else {
            for (prop in a) {
                if (a[prop] != b[prop]) {
                    return false;
                }
            }

        }
        return true;
    }
    return this.filter(function (item, index, list) {
        for (var i = 0; i < index; i++) {
            if (compare(item, list[i])) {
                return false;
            }
        }
        return true;
    });
};

var uniqueName = list.uniqueObjects(["name"]);
var uniqueAge = list.uniqueObjects(["age"]);
var uniqueObject = list.uniqueObjects(["name", "age"]);

http://jsbin.com/ahijex/4/edit

like image 122
Diode Avatar answered Oct 18 '25 07:10

Diode



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!