Web Developer Web Developer - 6 months ago 27
Node.js Question

`map` and `filter` in javascript

Having the following input:

var m = [{
name: 'foo',
routes: [{verb: 'post', path: '/foo1'},
{verb: 'get', path: '/foo2'}]
}, {
name: 'bar',
routes: [{verb: 'put', path: '/:id'}]},
{
name: '__ignoreme',
routes: [{verb: 'post', path: '/baz1'},
{verb: 'get', path: '/baz2'}]
}]


Using
map
and
filter
I want to achieve:

var desired = [
'foo POST /foo1',
'foo GET /foo2',
'bar PUT /:id',
]


Complete code:

var m = [{
name: 'foo',
routes: [{verb: 'post', path: '/foo1'},
{verb: 'get', path: '/foo2'}]
}, {
name: 'bar',
routes: [{verb: 'put', path: '/:id'}]},
{
name: '__ignoreme',
routes: [{verb: 'post', path: '/baz1'},
{verb: 'get', path: '/baz2'}]
}]



var desired = [
'foo POST /foo1',
'foo GET /foo2',
'bar PUT /:id',
]


var myOutput = m
.filter(function (m) {
return m.name.indexOf('__') === -1;
})
.map(function (m) {
return [
m.name,
m.routes[0].verb.toUpperCase(), // I should loop through my array instead of getting just the first element
// But can I loop through the array in my map?
m.routes[0].path
].join(' ');
});


console.log('>myOutput:', myOutput);
// What I achieve which is not desired :
// [
// 'foo POST /foo1',
// 'foo PUT /:id',
//]


This is the structure which is is used in my code and I want to achieve my desired output with the small change and still using
map
and
filter
.

Answer

You can use a loop inside of the map function to ensure you look at all routes for a given name. That will return an array of arrays, so I used reduce after the map to flatten that into a single array of strings.

var myOutput = m
        .filter(function (m) {
          return m.name.indexOf('__') === -1;
        })
        .map(function (m) {
          var arr = [];
          for(var i = 0; i < m.routes.length; i++){
            arr.push([
              m.name,
              m.routes[i].verb.toUpperCase(),            
              m.routes[i].path
            ].join(' '));
          }
          return arr;
        }).reduce(function(prev, cur){
          return prev.concat(cur);
        });

This results in myOutput of ["foo POST /foo1", "foo GET /foo2", "bar PUT /:id"].

Comments