我有这两个数组:
const data = [
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
]
const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
]
我想测试数组locationComment
+1中的com
是否等于数组locationMethod
中的data
,如果是,那么我想拥有像这样的东西:
const array = [
{type: 'type2', name: "com1"},
{type: 'type3', name: "com2"}
]
这是我的代码:
const result = data.map((x)=>{
const arr = [];
com.map((y)=>{
if(x.location == y.location+1){
arr.push({
type: x.type,
name: y.name,
location: x.location
})
}
})
return arr;
});
这是我得到的输出:
[ [],
[ { type: 'type2', name: 'com1', location: 37 } ],
[ { type: 'type3', name: 'com2', location: 61 } ],
[] ]
答案 0 :(得分:2)
由于不确定com
数组中的每个元素是否都匹配,因此应使用reduce
:
const data = [
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
];
const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
];
const output = com.reduce((a, { name, location }) => {
const found = data.find(item => item.location === location + 1);
if (found) {
a.push({ type: found.type, name });
}
return a;
}, []);
console.log(output);
如果location
是唯一的,则可以通过将O(N)
首先转换为data
索引的对象来将时间复杂度降低到location
:
const data = [
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
];
const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
];
const dataByLoc = data.reduce((a, item) => {
a[item.location] = item;
return a;
}, {});
const output = com.reduce((a, { name, location }) => {
const found = dataByLoc[location + 1];
if (found) {
a.push({ type: found.type, name });
}
return a;
}, []);
console.log(output);
答案 1 :(得分:1)
如果单行解决方案不适合您,则下面的代码也应该结合使用.map()和.find()来工作。
const data = [
{ type: 'type1', location: 23 },
{ type: 'type2', location: 37 },
{ type: 'type3', location: 61 },
{ type: 'type4', location: 67 }
]
const com = [
{ name: "com1", location: 36 },
{ name: "com2", location: 60 }
]
// Final Array Output with merged properties
let finalArr = []
data.forEach(locationMethodObj => {
// Fetching the type
let finalObj = {
type: locationMethodObj.type
}
// Checking if a location match exists
const foundObj = com.find(locationCommentObj => (locationCommentObj.location + 1) ===
locationMethodObj.location
)
// If a match is found, then append name and push
if(foundObj){
finalObj.name = foundObj.name
finalArr.push(finalObj)
}
})
console.log(finalArr)