How to make a JSON array unique [duplicate]

2019-01-28 09:03发布

问题:

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",product="foo"},
 Object { id="38",product="foo"},
 Object { id="39",product="bar"},
 Object { id="40",product="hello"},
 Object { id="40",product="hello"}

]

There are duplicate values in this JSON array..how can i make this JSON array unique like this

[
 Object { id="38",product="foo"},
 Object { id="39",product="bar"},
 Object { id="40",product="hello"}
]

.Im looking for a suggestion that uses less iterations, Jquery $.inArray is not working in this case.

Suggestion to use any third party libraries are welcome.

回答1:

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.



回答2:

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;
});


回答3:

// 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);



回答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:

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


回答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;
        return val;
    }
});
helper = null;