content/snippets/js/s/code-anatomy-chaining-reduce-for-loop.md
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}`;
filePaths.push(filePath);
}
}
// filePaths = [ '~/cool_app/foo.txt', '~/cool_app/.bar', '~/cool_app/baz.foo']
for loop can be used - read more about the different JavaScript loops.returns.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}`;
acc.push(filePath);
}
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).