问题
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