Created
December 18, 2019 02:33
-
-
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
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
/** | |
* 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