Array.prototype.exists()

Wouldn't it be nice if we can find out if at least one object with specific caracteristics (properties) is included inside an array.
Like Array.includes(item) we can use to discover if an element currently exists inside an array, we would be able to determine if an object with specific catacteristics is listed inside the array.
The point is that every time I need to investigate an array of objects if a specific object containing specific properties I use the Array.findIndex(obj => obj.a === object.a && obj.b === object.b && ...) !== -1.

I would propose someting like this:

Array.exists({...object.properties})

The exists() method checks if one elements in an array has the properties with specified values.

The exists() method executes the function once for each element present in the array:

  • If it finds an array element where the object matches values, exists() returns true (and does not check the remaining values)
  • Otherwise it returns false

If you know you’re not looking for undefined, find should work fine in a truthy context, without the comparison.

Hi!

You should use the some method instead to check for existence of an array element matching your criteria:

arr.some(obj => obj.a === object.a && obj.b === object.b && ...)

If you don't want to spell out all these property comparisons manually, you can use a helper function for that:

function matches(object) {
  return target => {
    for (const p in object) if (object[p] !== target[p]) return false;
    return true;
  };
}
console.log(arr.some(matches(objects.properties)));
1 Like

Perfect!
Never used .some(), and there it is... the answer to what I need.
Thanks a lot!!!

1 Like