HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Code Anatomy - For loops, array reduce and method chaining

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptloopsreduceandmethodchaininganatomycodearrayfor

Problem


  • Any for loop can be used - read more about the different JavaScript loops.
  • Less common nowadays, due to functional programming being more popular.
  • Control over the iteration, such as skipping over elements or early returns.
  • Resulting array needs to be declared beforehand, outside the loop.
  • Uses Array.prototype.push() or the spread (...) operator to add elements.

Solution

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']


  • Control over the iteration, such as skipping over elements or early returns.
  • Resulting array needs to be declared beforehand, outside the loop.
  • Uses Array.prototype.push() or the spread (...) operator to add elements.
  • O(N) complexity, each element will be iterated over only once.
  • Uses Array.prototype.reduce() with an empty array as the initial value.
  • More common nowadays, due to functional programming being more popular.

Code Snippets

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']
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']
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']

Context

From 30-seconds-of-code: code-anatomy-chaining-reduce-for-loop

Revisions (0)

No revisions yet.