Skip to content

Instantly share code, notes, and snippets.

@shiv19
Created December 18, 2019 02:33
Show Gist options
  • Save shiv19/92eb4491385e202f3f422cc15e5d4cf1 to your computer and use it in GitHub Desktop.
Save shiv19/92eb4491385e202f3f422cc15e5d4cf1 to your computer and use it in GitHub Desktop.
Tells you what's different in the incoming array when compared to exisiting array
/**
* Tells you what's different in the incoming array when compared to exisiting array
* Either pass in array of objects or pass in array of strings. Don't pass mixed array.
*
* @param incomingArray
* @param existingArray
* @param {'object'|'string'} compareType
*/
function difference(incomingArray, existingArray, compareType = 'object') {
const convertToStringIfNecessary = v => compareType === 'object' ? JSON.stringify(v) : v;
const convertToObjectIfNecessary = v => compareType === 'object' ? JSON.parse(v) : v;
const incoming = JSON.parse(JSON.stringify(incomingArray)).map(convertToStringIfNecessary);
const existing = JSON.parse(JSON.stringify(existingArray)).map(convertToStringIfNecessary);
const result = [];
for (let i = 0; i < incoming.length; i++) {
if (existing.indexOf(incoming[i]) === -1) {
result.push(incoming[i]);
}
}
return result.map(convertToObjectIfNecessary);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment