Search code examples
javascriptlodash

add an object to an array if it doesn't have the same key with one of the objects in the array


I'm using Lodash. I have the array below:

const array = [{id:1,name:a},{id:2,name:b},{id:3,name:c},{id:4,name:d},{id:5,name:e}];

and I'm about to add another object to this array but before that, I need to check if the new object's name is already in the array or not and if there is one with the name I won't add the new object anymore. I know some ways to do it, for instance, a loop with _.map, but want to make sure if there is an easier way.


Solution

  • You could use Lodash's some which if provided with an appropriate predicate e.g. (item => item.name === newName) will return a boolean indicating whether or not the item already exists (in this case, true would mean the name already exists). The benefit of using this over other iterating methods is that it will stop as soon as it finds one that returns true resulting in better performance.