Almost in every application or webpart, any developer would be dealing with the Array and any type of collection. There are few scenarios which I faced with respect to the Difference, Union etc., Just wanted to share with the audience.
For the below article, let us use the basic Arrays. I have two Array of file names.
One with the total files which I have in a document library.
allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
The Second one, only the required files.
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
Difference
Basically, I need to delete the files “File1, File3 and File4”. To identify that, doing a for loop and all, I don’t want to do that. The simplest way is as below.
allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let filesToBeDeleted = allFilesInsideFolder.filter(x => !filesToCopy.includes(x));
filesToBeDeleted = [‘File1.txt’,‘File3.txt’, ‘File4.txt’]
Intersection
May be, in some scenario if I want only the files which are available on both the array, then
allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let intersectionFiles = allFilesInsideFolder.filter(x => filesToCopy.includes(x));
intersectionFiles = [ ‘File2.txt’, ‘File5.txt’]
Symmetric Difference
In case, if I want only the unique files, i.e., any file which is present either in allFilesInsideFolder or filesToCopy array, then
allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let symmetricdifference = allFilesInsideFolder
.filter(x => ! filesToCopy.includes(x))
.concat(filesToCopy.filter(x => ! allFilesInsideFolder.includes(x)));
symmetricdifference = [ ‘File1.txt’, ‘File3.txt’,‘File4.txt’,‘File6.txt’]
Union
In case, if I want both the array elements, then
allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let union = [...allFilesInsideFolder, ... filesToCopy];
union = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’, ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
This will have duplicates. But the distinct union will not have duplicates.
Distinct Union
If I want the distinct elements in both the arrays, then
allFilesInsideFolder = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’]
filesToCopy = [ ‘File2.txt’, ‘File5.txt’, ‘Files6.txt’]
let distinctunion = [...new Set([...allFilesInsideFolder, ... filesToCopy)];
distinctunion = [‘File1.txt’, ‘File2.txt’, ‘File3.txt’, ‘File4.txt’, ‘File5.txt’, ‘Files6.txt’]
Happy Coding
Sathish Nadarajan
Leave a comment