Reputation:
I have an arrayList with objects in it. I need to show only one value, if objects has the same values.
For Example : [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ] From the above example I need to show only the first and second object and skip the third object because it is as same as first object.
Note : the objects in array can be infinite, I cant hardcode the index value. Can anyone help me out the generic solution.
This is what I have tried:
points = [];
newarr = [];
locArray = [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ];
if(abc!=null){
removeDuplicateCoordinates();
$.each(newarr,function(key,val){
points.push([val.a,val.b]);
});
}
function removeDuplicateCoordinates(){
var arr = locArray;
$.each(arr, function(index,item){
if(searchForItem(newarr,item)<0){
newarr.push(item);
}
});
}
function searchForItem(array, item){
var i, j, current;
for(i = 0; i < array.length; ++i){
if(item.length === array[i].length){
current = array[i];
for(j = 0; j < item.length && item[j] === current[j]; ++j);
if(j === item.length)
return i;
}
}
return -1;
}
Upvotes: 3
Views: 1376
Reputation: 5577
One of my favorite methods:
usedArray = {};
locArray = [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ];
for (key in locArray) {
if (usedArray[JSON.stringify(locArray[key])] == undefined) {
console.log(JSON.stringify(locArray[key]));
usedArray[JSON.stringify(locArray[key])] = true;
}
}
Don't know anything about how fast it is, but it works for me everytime. Working fiddle.
instead of console.log(JSON.stringify(locArray[key]));
You can populate new array:
newarr.push(locArray[key]);
EDIT
Test width 100000 objects in fiddle ~300ms i can live with that.
Upvotes: 1
Reputation: 1589
First of all Array.indexOf() will not compare objects.
In JavaScript objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.
So, easiest and fastest way IMHO, will be to compare by yourself. Here is the working JSFiddle
var locArray = [{ a: 0, b: 1 }, { a: 1, b: 0 }, { a: 0, b: 1 }];
//We will try to find if point alrady exists in array
Array.prototype.indexOfPoint = function(point) {
for (var i = 0; i < this.length; i++) {
var arrPoint = this[i];
if (arrPoint.a === point.a && arrPoint.b === point.b)
return i;
}
return -1;
};
Array.prototype.uniquePoints = function() {
var a = [];
for (var i = 0; i < this.length; i++) {
var currentPoint = this[i];
if (a.indexOfPoint(currentPoint) < 0) {
a.push(currentPoint);
}
}
return a;
};
var newarr = locArray.uniquePoints();
console.log(newarr);
Upvotes: 0
Reputation: 2200
Fiddle Demo
try this one
newarr = [];
testarr = [];
locArray = [ {a:0,b:1},{a:1,b:0},{a:0,b:1} ];
for (var i = 0; i<locArray.length;i++)
{
var idx = $.inArray(String(locArray[i].a)+String(locArray[i].b), testarr);
if (idx == -1) {
testarr.push(String(locArray[i].a)+String(locArray[i].b));
newarr.push(locArray[i]);
}
}
console.log(newarr);
Upvotes: 2