Click here to Skip to main content
15,917,568 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Need to remove duplicates in arraylist in javascript...

<!DOCTYPE html>


Try it



function myFunction() {
var array =
[
{"name":"Bob", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
];

var t = [];
for (var x = 0; x &lt; array.length; x++) {
if (t.indexOf(array[x].name) == -1) t.push(array[x].name);
}


//My expect results
var t =
[
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
];
}




What I have tried:

I have tried the below code...
plz help..
thanks Advance
Posted
Updated 26-Jul-18 22:31pm
Comments
venkatesh (chennai) 27-Jul-18 6:10am    
// Removed Duplicate values
var result = array.filter(function (el, i, x) {
return x.some(function (obj, j) {
return obj.name === el.name && (x = j);
}) && i == x;
});

1 solution

The problem you have here is that you are just pushing the name. More importantly, you are going to face an issue where what you are trying to find is a complex type so you are going to have to roll your own implementation. Fortunately, that's a pretty trivial thing to do. First of all, you would simply add your own version of indexOf (something like this will do):
JavaScript
Array.prototype.complexIndexOf = function(type) {
  for (var x = 0; x < this.length; x++) {
    if (this[x].id === type.id && this[x].name === type.name)
	  return i;
  }
  return -1;
}
With this prototype in place, you simply change the condition in your for loop to:
JavaScript
if (t.complexIndexOf(array[x]))t.push(array);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900