Compare objects in two arrays and return based on match in javascript

后端 未结 3 606
梦谈多话
梦谈多话 2021-01-29 00:34

I am using React for this, but the concept is in javascript. So hopefully I can leave React code out for simplicity sake.

I have two arrays that I need to filter out. My

3条回答
  •  春和景丽
    2021-01-29 01:03

    Your problem is you are comparing index-by-index. You want to know if the element in arr1 is anywhere in arr2, right?

    I would use arr2.filter to search all of arr2. So you would have something like this:

    return arr1.map((e1, i) => {
      if (arr2.filter(e2 => e2.id === e1.id).length > 0) {  // If there's a match
        return 
    Match
    } else { return
    No Match
    } })

    UPDATE: As recommended in the comments using Array.some is better here:

    return arr1.map((e1, i) => {
      if (arr2.some(e2 => e2.id === e1.id)) {  // If there's a match
        return 
    Match
    } else { return
    No Match
    } })

提交回复
热议问题