1

The following method seems a little naive to me so I am wondering if there is a better way to do this. 2 arrays are involved and they contain objects which I have to compare by a certain property:

function exists(objArray, id) {
    var isFound = false;
    objArray.forEach(obj => {
        if (obj.Id == id)
            isFound = true;
    });

    return isFound;
}

var array1, array2;
array1.forEach(obj => exists(array2, obj.Id));
Michael Munta
  • 207
  • 2
  • 16

2 Answers2

4

Use .some instead.

const exists = (objArray, id) => objArray.some(obj => obj.Id === id);

(I'd highly recommend using strict equality === and not sloppy equality if at all possible)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Can you elaborate on why force strict equality? – Michael Munta Jun 02 '21 at 18:29
  • Because https://stackoverflow.com/a/23465314 It's way too confusing to use sloppy equality – CertainPerformance Jun 02 '21 at 18:30
  • Using strick equally will check for both the data-type and the value while the other will ignore data-type and only compare value which does not always guarantee correctness. – Wale Jun 02 '21 at 18:34
  • Note that while this does short-circuit once it finds a match (a good thing!), in the long run it's still the same performance characteristics as the OP. – y2bd Jun 02 '21 at 18:58
  • @y2bd performance-wise, is there anything better? – Michael Munta Jun 02 '21 at 19:01
  • 2
    @MichaelMunta A `for` loop can be faster than `forEach` or anything else - but it's less readable. Performance is almost never an issue to be concerned about. Prioritize clean, readable code first. Only if a section of code proves to be a problem should readability be sacrificed, in most cases. – CertainPerformance Jun 02 '21 at 19:17
0

You can use lodash's differenceWith by passing a comparator function to check if two arrays have a common object.

comparator(obj1, obj2){
  return obj1.id !== obj2.id;
}

let arr1 = [{id: 1}]
let arr2 = [{id: 2}]
_.differenceWith(arr1, arr2, comparator)

It returns an empty array if no matching elements, else returns the object with matching id of first array

Kabita
  • 1