claudio3949
claudio3949

Reputation: 27

map, filter and own value

I have: stackoverflow.com/questions/19012903/get-value-from-multi-object but i modified this and i would like add to results string longer than 4 chars.

function isLong(val)
{
    if(val.length > 4){
       return true;
    } else {
        return false;
    }
}

var page = [{
    title: 'aaa',
    text: '111'
}, {
    title: 'bbb',
    text: '222'
}, {
    title: 'ccc',
    text: '333'
}, {
    title: 'ddd',
    text: '444'
}, {
    title: 'eee',
    text: '444'
}];

console.log([].concat.apply([], '222, 333, 4441, long1, long, long2'.split(', ').map(function (t) {
    return page.filter(function (o) {
        return o.text === t || isLong(t);
    }).map(function (c) {
        return c.title
    });
})).join(", "));

jsfiddle

but this return me all values. I try check this in line return o.text === t || isLong(t);

For this example i would like receive:

bbb, ccc, long1, long2

bbb and ccc are from object page. long1 and long2 are form my custom string separated by commas.

Upvotes: 0

Views: 58

Answers (1)

Cristi Pufu
Cristi Pufu

Reputation: 9095

var str = '222, 333, 4441, long1, long, long2';

var strArray = str.split(', ');

var result = strArray.map(function(s){
    return isLong(s) ? s : page.filter(function(o){ // if word has > 4 chars return word else try to match with page array
       return o.text == s; 
    }).map(function(c){
      return c.title;  // if matched return title
    })[0]; // select first match
}).filter(function(u){
    return u;  // remove undefined results
});

console.log(result);

Example: http://jsfiddle.net/YrZNq/6/

Upvotes: 1

Related Questions