How to compare 2 arrays for same value and save them to 3rd array with true or false flags

落花浮王杯 提交于 2021-01-29 21:26:26

问题


I have 2 arrays:

var arr1 = [{name:"Option1"},{"name":"Option2"},{"name":"Option3"},{"name":"Option4"},{"name":"Option5"},{"name":"Option6"},{"name":"Option7"},{"name":"Option8"},{"name":"Option9"},{"name":"Option10"}]

var arr2 = [{"name": "Option 2"},{"name": "Option 4"},{"name": "Option 6"},{"name": "Option 8"},{"name": "Option 10"}]

What I wish to achive is that a 3rd array with all the values from arr1 with additional flag of "marked":true if that value is found in arr2 ELSE "marked": false

I tried a various combination of arry methods such as map(), filter(), forEach() but somehow not able to figure out how to return properly without repeating the values or making duplicate entries.

** What I see is that my inside and outside loop both statements are executed and I somehow miss the return true / false logic and end up repeating my loop the number of time equal to the length of arr2. **

function test() {
  var arr1 = [{
      name: "Option1"
    },
    {
      "name": "Option2"
    },
    {
      "name": "Option3"
    },
    {
      "name": "Option4"
    },
    {
      "name": "Option5"
    },
    {
      "name": "Option6"
    },
    {
      "name": "Option7"
    },
    {
      "name": "Option8"
    },
    {
      "name": "Option9"
    },
    {
      "name": "Option10"
    }
  ]
  var arr2 = [{
      "name": "Option2"
    },
    {
      "name": "Option4"
    },
    {
      "name": "Option6"
    },
    {
      "name": "Option8"
    },
    {
      "name": "Option10"
    }
  ]
  arr1.forEach((el) => {
    arr2.forEach((el2) => {
      if (el.name.toString() === el2.name.toString()) {
        return console.log("Printing from inside the if loop", el)
      }
      console.log("Printing from outside the if loop", el)
    })
  })
}
test()

回答1:


Start by mapping all the comparison values (name) from arr2 into a Set.

Then map arr1 to create the new array and lookup each name in the arr2 Set

const arr2Names = new Set(arr2.map(e => e.name));

const res = arr1.map(e => ({...e, marked: arr2Names.has(e.name)}));

console.log(res)
<script>
var arr1=[{name:"Option1"},{name:"Option2"},{name:"Option3"},{name:"Option4"},{name:"Option5"},{name:"Option6"},{name:"Option7"},{name:"Option8"},{name:"Option9"},{name:"Option10"}],
arr2=[{name:"Option2"},{name:"Option4"},{name:"Option6"},{name:"Option8"},{name:"Option10"}];
</script>


来源:https://stackoverflow.com/questions/64529536/how-to-compare-2-arrays-for-same-value-and-save-them-to-3rd-array-with-true-or-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!