2
\$\begingroup\$

I need to first filter items for an array of objects {type: 'genre', value: '123'} and after combine in a string content for property value only.

Any suggestions on how to improve the following code?

this.flattenCategories = function () {
    // flatten in a single string all categories so to be easily visaulised in the dom
    var categories = this.information.filter(function (item) {
        if (item.type === 'genre') {
            return item;
        }
    });
    this.categoriesFlatten = categories.map(function (item) {
        return item.value;
    }).join(CONFIG.app.categoriesSeparator)
},
\$\endgroup\$
3
\$\begingroup\$

I would replace the filter and the map by a reduce:

this.flattenCategories = function () {
  // flatten in a single string all categories so to be easily visualised in the dom
  return this.information.reduce( function( categories , item ){
    if( item.type === 'genre' ){
      categories.push( item.value );
    }
    return categories;
  }, []).join(CONFIG.app.categoriesSeparator);
},

This way your code is still functional, you loop over the data only once, and your intent is clearer.

categoriesSeparator seems such a specific constant that I wonder if you collect all your constants in 1 single place, J2EE style.. That's not really idiomatic JavaScript, try to define your constant closer to where you will actually use it.

\$\endgroup\$
4
\$\begingroup\$

You have a bug in your code. Filter expects true or false. Your still works because implicit type conversion of Javascript (object => true, undefined => false).

Correct would be:

var categories = this.information.filter(function (item) {
    return item.type === 'genre';
});

Filter/Map could be combined together if you like.

You're using variable from outside. You could improve testability and readability by using of arguments and return the result.

this.flattenCategories = function (information, separator) {
    // flatten in a single string all categories so to be easily visaulised in the dom
    return information
        .filter(function (item) { return item.type === 'genre'; })
        .map(function (item) { return item.value; })
        .join(separator);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.