簡體   English   中英

如何有條件地加入兩個數組

[英]How to join two arrays conditionally

我想有條件地加入兩個數組:

aData = [ { id: 1, title: `bla`}, { id: 2, title: `la`}, { id: 3, title: `lala`} ]
bData = [ { id: 1, description: `bla`} ]

在第一種情況下,我希望僅能獲得具有合並屬性的匹配結果( aData+bData

matchingIdsResult = [ { id: 1, title: `bla`, description: `bla` } ]

在第二種情況下,我想要不匹配的結果-來自aData對象,其ID在bData中沒有bData

unmathingIdsResult = [ { id: 2, title: `la`}, { id: 3, title: `lala`} ]

到目前為止,我正在使用.map.reduce實現:

const data: any = aData.concat(bData).reduce((acc, x) => {
    acc[x.id] = Object.assign(acc[x.id] || {}, x);
    return acc;
}, {});

但是在那種情況下,到目前為止,我確實將所有aData對象與匹配的bData屬性合並在一起,這並不是我真正想要的。

通過bDataid創建一個Map reduce迭代aData 如果bDataMap一個對象idbDataMap合並的對象推入第一個子數組。 如果不是,請到第二。 獲取matchingIdsResultunmatchingIdsResult通過解構的減少的結果:

 const aData = [{"id":1,"title":"bla"},{"id":2,"title":"la"},{"id":3,"title":"lala"}]; const bData = [{"id":1,"description":"bla"}]; const bDataMap = new Map(bData.map((o) => [o.id, o])); const [matchingIdsResult, unmatchingIdsResult] = aData.reduce((r, o) => { if(bDataMap.has(o.id)) r[0].push(Object.assign({}, o, bDataMap.get(o.id))); else r[1].push(o); return r; }, [[], []]); console.log(matchingIdsResult); console.log(unmatchingIdsResult); 

如果要跳過bDataMap的創建,可以使用Array.find() 復雜度將變為O(n * m),而不是Map(n-aData.length,m-bData.length)的o(n + m),但是對於小數組而言,這可以忽略不計:

 const aData = [{"id":1,"title":"bla"},{"id":2,"title":"la"},{"id":3,"title":"lala"}]; const bData = [{"id":1,"description":"bla"}]; const [matchingIdsResult, unmatchingIdsResult] = aData.reduce((r, o) => { const match = bData.find(({ id }) => id === o.id); if(match) r[0].push(Object.assign({}, o, match)); else r[1].push(o); return r; }, [[], []]); console.log(matchingIdsResult); console.log(unmatchingIdsResult); 

您可以將第一個數組作為不匹配的起始值,然后檢查第二個並拆分匹配的對象或推送到不匹配的數組。

 var aData = [{ id: 1, title: 'bla' }, { id: 2, title: 'la' }, { id: 3, title: 'lala' }], bData = [{ id: 1, description: 'bla' }], unmatching = aData, matching = []; bData.forEach(o => { var index = unmatching.findIndex(({ id }) => o.id = id); if (index === -1) { unmatching.push(o); } else { matching.push(Object.assign({}, unmatching.splice(index, 1)[0], o)); } }); console.log(matching); console.log(unmatching); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

創建一個不匹配和匹配檢查的映射,只要id存在即可。

並且當您擁有兩個單獨的matchedunmatched ,只需將matched數組(基於ID )與另一個包含數據的數組合並即可。

 aData = [ { id: 1, title: `bla`}, { id: 2, title: `la`}, { id: 3, title: `lala`} ] bData = [ { id: 1, description: `bla`} ]; var unmatched = [], matched = []; aData.every(x=> bData.map(e=> e.id).includes(x.id) ? matched.push(x) : unmatched.push(x)) matched = matched.map(x=> Object.assign(x, bData.find(e=> e.id ===x.id ))) console.log("Matched " , matched) console.log("Un matched", unmatched) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM