2
\$\begingroup\$

This code works just fine, but could obviously be more elegantly written.

The basic idea is to create an array of categories from a text input. The code splits up the text input by commas to create the array and trims away white space.

I considered using unshift to add the 'Inbox' default category to the beggining, but figure there must be an even better way. All in all, this is probably the 4th or 5th version of this code.

 var CategoriesForm = event.target.category.value;
 var CategoriesFormTrimmed = CategoriesForm.replace(" ", "");
 var categoriesDefault = ['Inbox']; //default category
 var categoriesJoined = [];
 if (CategoriesForm) {
 var splitUpCategories = CategoriesFormTrimmed.split(',');
 categoriesJoined = categoriesDefault.concat(splitUpCategories);
 console.log(categoriesJoined);
 } else {
 categoriesJoined = ['Inbox'];
 }

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Aug 27, 2015 at 5:21
\$\endgroup\$
1
  • \$\begingroup\$ Minor quibble: JavaScript conventionally uses camelCase for everything except constructor functions. So style-wise, your CategoriesForm should be categoriesForm, and the same for the -Trimmed var. Joseph's answer below sidesteps all those variables anyway, but just as a general note. \$\endgroup\$ Commented Aug 27, 2015 at 8:50

1 Answer 1

4
\$\begingroup\$

That same operation can be streamlined into:

var categoriesJoined = event.target.category.value
 .split(',')
 .map(function(category){ return category.trim(); })
 .filter(function(category){ return !!category; })
 .concat(['Inbox']);

or Inbox first:

var categoriesJoined = ['Inbox'].concat(event.target.category.value
 .split(',')
 .map(function(category){ return category.trim(); })
 .filter(function(category){ return !!category; }))
  • We split first by , giving us access to an array.
  • We clean up each item using map by returning a cleaned value using trim
  • Then filter out those who are totally whitespace (they end up as blanks when trimmed).
  • Add in "Inbox".
answered Aug 27, 2015 at 7:09
\$\endgroup\$
1
  • \$\begingroup\$ Awesome! This is super helpful. \$\endgroup\$ Commented Aug 27, 2015 at 16:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.