0

I try to make a unique array of objects. I try a lot of solution. Finaly a write a function. It works, but there is other solution? And whay $.unique dont work?

var a = [{"id": "id1", "name": "id1"},{"id": "id1", "name": "id1"},{"id": "id2", "name": "id2"}];
var jq = $.unique(a);
console.log("jq=",jq); // NOT UNIQUE!?
var myfunc = unique(a);
console.log("myfunc=",myfunc); // UNIQUE!

function unique(arr){
    var uniqueArr=[];
    var jsonarr = [];
    $.each(arr,function(ax, a){
        var j = JSON.stringify(a);
        if( jsonarr.indexOf(j) == -1 ){
            jsonarr.push(j);
            uniqueArr.push(a);
        }
    });
    return uniqueArr;
}   
IfThenElse
  • 485
  • 5
  • 13
  • https://stackoverflow.com/questions/23507853/remove-duplicate-objects-from-json-array – Alive to die - Anant Dec 16 '17 at 09:21
  • 2
    As for why $.unique() isn't working, according to the jQuery documentation, this is used to sort an array of DOM elements. Given that you're not providing it an array of DOM elements, that's likely why it's not working. See https://api.jquery.com/jQuery.unique/ – JoshG Dec 16 '17 at 09:32

1 Answers1

0

lodash library has a implimentation

_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
zabusa
  • 2,520
  • 21
  • 25