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;
}   
2
  • stackoverflow.com/questions/23507853/… Commented Dec 16, 2017 at 9: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 api.jquery.com/jQuery.unique Commented Dec 16, 2017 at 9:32

1 Answer 1

0

lodash library has a implimentation

_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// => [{ 'x': 1 }, { 'x': 2 }]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.