Skip to content Skip to sidebar Skip to footer

How To Make A Json Array Unique

Possible Duplicate: Array unique values Get unique results from JSON array using jQuery Im having a JSON string like this [ Object { id='38',product='foo'}, Object { id='38',p

Solution 1:

You can use underscore's uniq.

In your case, you need to provide an iterator to extract 'id':

array = _.uniq(array, true/* array already sorted */, function(item) {
  return item.id;
});

Solution 2:

// Assuming first that you had **_valid json_**
myList= [
    { "id":"38","product":"foo"},
    { "id":"38","product":"foo"},
    { "id":"38","product":"foo"},
    { "id":"39","product":"bar"},
    { "id":"40","product":"hello"},
    { "id":"40","product":"hello"}
];

// What you're essentially attempting to do is turn this **list of objects** into a **dictionary**.var newDict = {}

for(var i=0; i<myList.length; i++) {
    newDict[myList[i]['id']] = myList[i]['product'];
}

// `newDict` is now:console.log(newDict);

Solution 3:

Check the solution in the following SO question:

Get unique results from JSON array using jQuery

You'll have to iterate through your array and create a new array which contains unique values.

Solution 4:

You will probably have to loop through removing the duplicates. If the items stored are in order as you have suggested, it's a simple matter of a single loop:

functionremoveDuplicates(arrayIn) {
    var arrayOut = [];
    for (var a=0; a < arrayIn.length; a++) {
        if (arrayOut[arrayOut.length-1] != arrayIn[a]) {
            arrayOut.push(arrayIn[a]);
        }
    }
    return arrayOut;
}

Solution 5:

You can easily code this yourself. From the top of my head this comes to mind.

var filtered = $.map(originalArray, function(item) {
    if (filtered.indexOf(item) <= 0) {
        return item;
    }
});

Or as suggested a more efficient algorithm specifically for the case at hand:

var helper = {};
var filtered = $.map(originalArray, function(val) {
    var id = val.id;

    if (!filtered[id]) {
        helper[id] = val;
        returnval;
    }
});
helper = null;

Post a Comment for "How To Make A Json Array Unique"