Using ES6 semantics (modern browser, transpiled code or latest node.js), you can more efficiently use a Set
object which will automatically keep duplicates out.
var files = new Set(['file1_1','file2_0','file3_3','file4_2','file5_6']);
var newFiles = ['file1_1', 'file2_0', 'file1_2', 'file3_5', 'file4_6'];
files.add(...newFiles);
sessionStorage.setItem('file-names', JSON.stringify(Array.from(files)));
Working demo: http://jsfiddle.net/jfriend00/7d1dy1p7/
MDN reference on the Set object
And, there are numerous polyfills for the Set object too as it is a generally useful concept, particularly for things like this. Here's one I've created: Mimicking sets in JavaScript?
Or, if you're trying to find out which items in the newFiles
list are actually new and not in the files
list already, then you can do that like this.
var files = new Set(['file1_1','file2_0','file3_3','file4_2','file5_6']);
var newFiles = ['file1_1', 'file2_0', 'file1_2', 'file3_5', 'file4_6'];
var uniqueNewFiles = newFiles.filter(function(item) {
return !files.has(item);
});
Then, afterwards to update the existing files list, you can add these to it:
files.add(...uniqueNewFiles);
Or, using a more capable Set object, you could do this:
var files = new Set(['file1_1','file2_0','file3_3','file4_2','file5_6']);
var newFiles = new Set(['file1_1', 'file2_0', 'file1_2', 'file3_5', 'file4_6']);
var uniqueNewFiles = newFiles.difference(files);