-4

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"}'
];
2

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.