const files = [ 'foo.txt ', '.bar', ' ', 'baz.foo' ];
let filePaths = [];
for (let file of files) {
const fileName = file.trim();
if(fileName) {
const filePath = `~/cool_app/${fileName}`;
.push(filePath);
filePaths
}
}
// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
for
loop can be used -
read more about the different JavaScript loops.
return
s.
Array.prototype.push()
or the spread
(...
) operator to add elements.
O(N)
complexity, each element will be iterated over only
once.
const files = [ 'foo.txt ', '.bar', ' ', 'baz.foo' ];
const filePaths = files.reduce((acc, file) => {
const fileName = file.trim();
if(fileName) {
const filePath = `~/cool_app/${fileName}`;
.push(filePath);
acc
}return acc;
, []);
}
// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
Array.prototype.reduce()
with an empty array as the
initial value.
return
early.
Array.prototype.push()
or the spread
(...
) operator to add elements.
O(N)
complexity, each element will be iterated over only
once.
const files = [ 'foo.txt ', '.bar', ' ', 'baz.foo' ];
const filePaths = files
.map(file => file.trim())
.filter(Boolean)
.map(fileName => `~/cool_app/${fileName}`);
// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
Array.prototype.map()
and
Array.prototype.filter()
.
return
early.
Array.prototype.push()
or the spread
(...
) operator.
O(cN)
complexity, c
iterations per element,
(c
: length of the chain).