What is the simplest way to prefix all strings in an array with a "!" (exclamation mark) in javascript?

373 Views Asked by At

I have two variables I use for when I want to either include or exclude system files (using minimatch glob syntax, where the ! stands for exclusion).

var systemFiles = ['node_modules/**/*', '.git/**/*'];
var ignoredSystemFiles = ['!node_modules/**/*', '!.git/**/*'];

But this feels a bit redundant. Is there a simple way to turn the systemFiles array into the ignoredSystemFiles array (i.e.: prefix all items in systemFiles with a !)?

I know !systemFiles does not work, but something as compact as this would be awesome, as it would allow me to eliminate the ignoredSystemFiles variable.

2

There are 2 best solutions below

0
On BEST ANSWER

You can use this

var systemFiles = ['node_modules/**/*', '.git/**/*'];
var ignoredSystemFiles = systemFiles.map(function(el) { return '!' + el } );
17
On

A simple loop should do it :

var ignoredSystemFiles = new Array(systemFiles.length);
for(var i = 0; i < systemFiles.length; i++) {
    ignoredSystemFiles[i] = '!' + systemFiles[i];
}

Or if you use a recent enough browser and don't care about ie < 9;

var ignoredSystemFiles = systemFiles.map(function(v) { return '!' + v; })