Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have following Array

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

I want create unique array by id key like following:

[
  '{"id":"item1","val":"Items"}',
  '{"id":"item2","val":"Items"}',
  '{"id":"item3","val":"Items"}'
];
share|improve this question
1  
    
Is x an array of strings or objects ? – Hmahwish 20 hours ago

You can use array.filter

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

var unique = x.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
})

console.log(unique);

share|improve this answer

If you could use jQuery:

var obj = {};
$.each(x,function(index,val){
 var temp = JSON.parse(val);
 obj[temp.id] = val;
})

var tempArray = [];

for(var i in obj){
tempArray.push(obj[i])
}

console.log(tempArray);
share|improve this answer

ES6 has been officially published one and half years ago, why not give it a try?

var unique = [...new Set(x)]

Set to remove the duplicates, ... to spread members in an iterable.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.