Hi! I wrote a solution that should be able to handle n-number of lines. Also it does not care if there are duplicate numbers or they are out of order. It just uses .map and .reduce.. probably it still could be optimized by using Set.
const lines = ['1,2,3,4,5,6', '2,4,6,7,8,9,10', '1,2,3,4,5,6,8'] const mapArrayToHashTable = items => { return items.reduce((last, item) => ({...last, [''+item]: item}), {}) } const getHashTable = line => { const textNumbers = line.split(',') const numbers = textNumbers.map(number => parseInt(number)) return mapArrayToHashTable(numbers) } const [firstTable, ...otherTables] = lines.map(getHashTable) const result = otherTables.reduce((last, table) => { const keyObjs = Object.keys(table).map(key => last[key] ? {[key]: last[key]} : {}) return keyObjs.reduce((last, keyObj) => ({...last, ...keyObj}), {}) }, firstTable) console.log(Object.values(result)) // returns [2,4,6]
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi! I wrote a solution that should be able to handle n-number of lines.
Also it does not care if there are duplicate numbers or they are out of order.
It just uses .map and .reduce.. probably it still could be optimized by using Set.