Check if object exists with property value 'x' in array in Javascript

I have many objects from which I am trying to filter out duplicates. When an object has a property, IMAGEURL , which is present in another object, I want to ignore this object and move on.

I use nodeJS for this, so if there is a library that I can use to simplify it, let me know.

Earlier, I did similar implementations, checking string values ​​in arrays, doing something like:

 var arr = ['foo', 'bar']; if(arr.indexOf('foo') == -1){ arr.push('foo') } 

But this will not work for objects, as far as I can tell. What are my options? Simply put:

 var obj1 = {IMAGEURL: 'http://whatever.com/1'}; var obj2 = {IMAGEURL: 'http://whatever.com/2'}; var obj3 = {IMAGEURL: 'http://whatever.com/1'}; var arr = [obj1, obj2, obj3]; var uniqueArr = []; for (var i = 0; i<arr.length; i++){ // For all the iterations of 'uniqueArr', if uniqueArr[interation].IMAGEURL == arr[i].IMAGEURL, don't add arr[i] to uniqueArr } 

How can i do this?

+7
javascript object arrays for-loop
source share
2 answers

You can simply use the inner loop (keeping track of whether we saw the loop using the seen variable - here you can use labels, but I find the variable method easier to read):

 for (var i = 0; i<arr.length; i++){ var seen = false; for(var j = 0; j != uniqueArr.length; ++j) { if(uniqueArr[j].IMAGEURL == arr[i].IMAGEURL) seen = true; } if(!seen) uniqueArr.push(arr[i]); } 
+12
source share

Here is a brief description:

 var uniqueArr = arr.filter(function(obj){ if(obj.IMAGEURL in this) return false; return this[obj.IMAGEURL] = true; }, {}); 

http://jsfiddle.net/rneTR/2

Note: this is concise, but the order is slower than the answer to the question .

See also: http://monkeyandcrow.com/blog/why_javascripts_filter_is_slow/

+3
source share

All Articles