Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push only unique elements in an array

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example 'id' is the key, so i don't want to store other json objects with 'item1' key.

x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]    

var clickId = // could be "item1", "item2"....
var found = $.inArray(clickId, x);  //
if(found >=0)
{
    x.splice(found,1);
}
else{
    x.push(new Item(clickId, obj)); //push json object
}
like image 385
smtp Avatar asked Jul 29 '15 19:07

smtp


1 Answers

would this accomplish what you're looking for? https://jsfiddle.net/gukv9arj/3/

x = [
    {"id":"item1","val":"Items"},
    {"id":"item1","val":"Items"},
    {"id":"item2","val":"Items"}
];    

var clickId = [];
var list = JSON.parse(x);
$.each(list, function(index, value){
    if(clickId.indexOf(value.id) === -1){
        clickId.push(value.id);
    }
});
like image 187
stackoverfloweth Avatar answered Sep 17 '22 17:09

stackoverfloweth