Thian Kian Phin Thian Kian Phin - 20 days ago 6
Javascript Question

remove duplicated array of object using normal for loop

I know there's a shortcut like using loadash's uniq but I try to remove duplicated array of object using a native for loop.

var json = [
{name:"james"},
{name:"james_x"},
{name:"jame"},
{name:"james_x"}
]

for(var i = 0;i<json.length-1;i++){
if(json[i].name == json[i+1].name){
json.splice(i,i);
}
}

console.log(json);


https://jsfiddle.net/8wwnvzoc/

I REALLY want to know what's wrong.

Answer

Try sorting the array before looping over it like this:

var json = [
{name:"james"},
{name:"james_x"},
{name:"jame"},
{name:"james_x"}
]

json = json.sort(function(a, b){a=a.name;b=b.name;return a<b?-1:a>b?1:0});

for(var i = 0;i<json.length-1;i++){
   if(json[i].name == json[i+1].name){
      json.splice(i,1);
   }
}

console.log(json);

Then, the equal values will be near each other so your algorithm will work as expected...

EDIT:

A possibly better approach, though not using a loop:

var json = [
{name:"james"},
{name:"james_x"},
{name:"jame"},
{name:"james_x"}
]

json = json
    .sort(function(a, b){a=a.name;b=b.name;return a<b?-1:a>b?1:0})
    .reduce(function(a, b){var n=a.length;if(n===0||a[n-1].name!==b.name)a[n]=b;return a},[]);

console.log(json);