1

I have some simple objects in an Array. I want to add new objects to the Array only if they are not already in it, based on an object property.

var o = {text: 'foo'} var a = [o] var checkExisting = function (list, obj) { list.forEach(function(elem) { if (elem.text === obj) { return true } } } checkExisting(a, 'foo') 

This doesn't work. I can't figure out why. Any help or alternatives would be great.

1
  • You try to compare 'foo' (a String) to foo (an Object) so it is falseCommentedOct 9, 2015 at 11:24

2 Answers 2

4

Because you can't return value from callback in forEach, you can use for, like this

var checkExisting = function (list, obj) { for (var i = 0, len = list.length; i < len; i++) { if (list[i].text === obj) { return true; } } } 
0
    1

    This can be done very similar to how you are but with .every() because .forEach() always returns undefined. So you can't chain it either.

    .every() runs a method over every element like .forEach() but if it receives a false value it will abort. Finally if every iteration returns true it will return true to the caller otherwise it will return false.

    Because we return false to make it abort when a value is found (so it wont keep iterating), we then have to flip the value it returns before we return it from checkExisting.

    So using that you could do something like:

    var checkExisting = function (list, obj) { return !list.every(function(elem) { return elem.text !== obj; }); } 

    Obviously you would have to extend that for error handling if the object doesn't have a property text etc. See fiddle: http://jsfiddle.net/reLsqhkm/ And docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.