Reputation: 3541
I'm trying to search for an object inside an array with the following code:
function countUniqueBoxes(array,key)
{
var output = [];
var value = false;
var obj = false;
for(var i = 0; i < array.length; ++i)
{
value = array[i][key];
obj = {'Box': value};
if(output[i] === obj)
{
continue;
}
else
{
output.push(obj);
}
}
return output;
}
The array that Is passed to this function, contains multiples objects, with duplicate values. As you can see, I Im trying to sort out the duplicates, and Insert the unique values, but Instead, ALL the values Is added to my output array, even the duplicate values.
If I do like this Instead:
for(var i = 0; i < array.length; ++i)
{
value = array[i][key];
if(output.indexOf(value) === -1)
{
output.push(value);
}
}
It works. The unique values are added to my output array. But I want add the values as objects to my array.
What Is wrong?
Upvotes: 0
Views: 61
Reputation: 1785
because you directly compare the objects in your code, you can try :
if(output[i] output[i]['Box'] === obj['Box'])
{
continue;
}
in your code you need to do another for loop in output to do the compare, like:
function isHasObj(output,obj){
for (var j = 0; j < output.length; ++j) {
if (output[j]['Box'] === obj['Box']) {
return true;
}
}
return false;
}
and change the if like:
if (isHasObj(output,obj)) {
continue;
}
else {
output.push(obj);
}
Upvotes: 1
Reputation: 12131
You are using strict comparison operator (===
) to compare two completely different objects. This will not work, i.e.
{} === {} // Never true!
If you need to sort out objects that look like duplicates, you will need to use another mechanism, like comparing the objects' properties instead.
I think it boils down to how you would like to define a "duplicate" object in your array. There are two possibilities:
Depending on your situation, the solution will vary greatly, but the generic approach would be a loop inside a loop - the main loop will take one object in the array and then loop through that same array once again to see if it is in the array more than once.
There is definitely room for optimisation. Perhaps you could even refactor your code to not allow an object to be inserted to the array if it looks like duplicate in the first place.
Upvotes: 6
Reputation: 874
You can convert the javascript object to json String then compare tow strings.
JSON.stringify(obj1) === JSON.stringify(obj2)
x = {a: 47, b: 2};
y = {b: 2, a: 47};
if(JSON.stringify(x) === JSON.stringify(y) ){
//true
}else{
//false
}
Upvotes: 0