[英]How to merge all arrays of an object array to get unique values?
我有一些這樣的數據:
const items = [
{ _id: '1', reference: ['abc'] },
{ _id: '2', reference: ['def'] },
{ _id: '3', reference: ['abc'] }
]
items
的長度總是不同的。
現在,我需要在單個數組中獲取所有唯一的參考字符串。 所以結果應該是
['abc', 'def']
因為'abc'
是重復項。
我試圖使用一個forEach()
循環:
const references = []
items.forEach(i => {
references.concat(i.reference)
})
console.log(references)
但是references
只會得到一個空數組結果。 此外,我沒有照顧重復...
我想使用ES6模式。 有了這個我知道我可以使用這樣的事情:
const array1 = ['abc']
const array2 = ['def']
const array3 = Array.from(new Set(array1.concat(array2)))
但是,即使我不知道項目數組中有多少個對象,我如何使用循環來獲取每個項目對象的每個引用數組呢?
如果要使用Sets,則可以使用Set.add
和Set.add
語法 :
const items = [ { _id: '1', reference: ['abc'] }, { _id: '2', reference: ['def'] }, { _id: '3', reference: ['abc'] } ] var references = new Set(); items.forEach(i => references.add(...i.reference)) console.log(Array.from(references))
如果您想執行功能性樣式(map-reduce),則可以這樣做
const items = [ { _id: '1', reference: ['abc'] }, { _id: '2', reference: ['def'] }, { _id: '3', reference: ['abc'] } ] // extract references and put them into a single array const references = items .map(x => x.reference) .reduce((prev, cur) => prev.concat(cur)) // put them in a set to dedupe const set = new Set(references) console.log(references) console.log([...set])
如果您希望對數據進行較少的傳遞,並且還可以避免使用Set
,則可以這樣做。
const items = [ { _id: '1', reference: ['abc'] }, { _id: '2', reference: ['def'] }, { _id: '3', reference: ['abc'] } ] const result = Object.keys(items.reduce((obj, {reference}) => { for (const ref of reference) { obj[ref] = true } return obj; }, {})) console.log(result)
您也可以使用下面的完全命令性方法來權衡表現力與性能。
const items = [ { _id: '1', reference: ['abc'] }, { _id: '2', reference: ['def'] }, { _id: '3', reference: ['abc'] } ]; const occ = {}; const references = []; for (let i = 0; i < items.length; ++i) { const refs = items[i].reference; for (let j = 0; j < refs.length; ++j) { const ref = refs[j]; if (occ[ref] == null) { references.push(ref); occ[ref] = true; } } } console.log(references)
這類似於此處的其他解決方案,但創建了可重用的函數:
const uniqRefs = items => [...items.reduce((s, i) => s.add(...i.reference), new Set())] const items = [{"_id": "1", "reference": ["abc"]}, {"_id": "2", "reference": ["def"]}, {"_id": "3", "reference": ["abc"]}] console.log(uniqRefs(items))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.