Created
November 6, 2021 18:58
-
-
Save yairEO/089506ba020b84003050a0d1ad01eeae to your computer and use it in GitHub Desktop.
Concatenates N arrays without dupplications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Concatenates N arrays without dups. | |
* If an array's item is an Object, compare by `value` | |
* @param {*} k | |
*/ | |
export const concatWithoutDups = (...key) => { | |
const result = (...args) => { | |
const newArr = [], | |
existingObj = {}; | |
for( let arr of args ) { | |
for( let item of arr ) { | |
// if current item is an object which has yet to be added to the new array | |
if( isObject(item) ){ | |
if( !existingObj[item[key]] || !key ){ | |
newArr.push(item) | |
existingObj[item[key]] = 1 | |
} | |
} | |
// if current item is not an object and is not in the new array | |
else if( !newArr.includes(item) ) | |
newArr.push(item) | |
} | |
} | |
return newArr | |
} | |
if( key.length > 1 ){ | |
let args = key; | |
key = null; | |
return result(...args) | |
} | |
else | |
key = key[0] | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without caring about duplicate objects
Skip objects with same key