[英]JS - compare 2 arrays by key, return 4 arrays: matches & unmatches from each
[英]TS (JS question) - Get 2 array of objects return 4 arrays - matches and unmatches from each one
界面 -
interface I {
name: string;
age: number;
size: string;
location?: string;
}
空 arrays -
let firstArrayMatches: I[] = [];
let firstArrayUnmatches: I[] = [];
let secondArrayMatches: I[] = [];
let secondArrayUnmatches: I[] = [];
Arrays -
const firstArray: I[] = [
{
name: 'daniel',
age: 30,
size: 'm'
},
{
name: 'tamir',
age: 30,
size: 'm'
},
]
const secondArray: I[] = [
{
name: 'daniel',
age: 30,
size: 's'
},
{
name: 'ariel',
age: 28,
size: 'm'
},
]
從第二個數組創建新的 map(忽略第二個字符串,它用於 mt 實際代碼中的其他內容) -
const map = new Map<string, string>(
secondArray.map(
({
name
}) => [
name,
'firstArray'
])
)
在第一個陣列上運行 -
for (const o of firstArray) {
const match = map.get(
o.name
)
if(match) {
firstArrayMatches.push(o);
} else {
firstArrayUnmatches.push(o);
}
}
日志 -
第一個數組 - console.log(JSON.stringify(firstArrayMatches))
"match: [{"name":"daniel","age":30,"size":"m"}]"
第二個數組 - console.log(firstArrayUnmatches)
[{
"name": "tamir",
"age": 30,
"size": "m"
}]
現在我的 function 只能從第一個數組返回匹配項和不匹配項,我怎樣才能獲得第二個數組匹配項和不匹配項?
僅當 secondArray 的名稱沒有重復項時,以下解決方案才有效。 (我希望它是因為您從中創建了 Map)
// create index of second array
const secondArrayIndexes = Array.from(map.keys());
// OR const secondArrayIndexes = secondArray.map(({ name }) => name);
for (const o of firstArray) {
// get index of o.name
const match = secondArrayIndexes.indexOf(o.name);
if (match >= 0) {
firstArrayMatches.push(o);
secondArrayMatches.push(...secondArray.splice(match, 1));
} else {
firstArrayUnmatches.push(o);
}
}
// finally secondArray become secondArrayUnmatches
// you should create copy first if you use secondArray after this
secondArrayUnmatches = secondArray;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.