Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created November 6, 2021 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/089506ba020b84003050a0d1ad01eeae to your computer and use it in GitHub Desktop.
Save yairEO/089506ba020b84003050a0d1ad01eeae to your computer and use it in GitHub Desktop.
Concatenates N arrays without dupplications
/**
* 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
}
@yairEO
Copy link
Author

yairEO commented Nov 6, 2021

Without caring about duplicate objects

concatWithoutDups([1,"a"], ["b",1,"a", {value:1}], [{value:1}, 7], [{value:2}])

Skip objects with same key

concatWithoutDups('value')([1,"a"], ["b",1,"a", {value:1}], [{value:1}, 7], [{value:2}])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment