xendi xendi - 8 months ago 79
Node.js Question

Javascript - How to get filter() to return match result

I need to return the result of

match
to
filter
. I tried
forEach
but it causes my script to crash without an error for some reason I can't seem to resolve. If within the
filter
I log
element.match(/regex/)[1]
it logs the output I want. When I return that however, it returns the whole string (Not just the match). Here's the code:

let myAr = ['{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"100000077777226","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AauUajLpeWuhLBG3jk4ypnhABBcEcbN4M8Z2F6J_CQaQXEhPwL-3j1_dX5vhAleK3K7rjlzqJwnG4xGGaGdFk7Eb","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
'{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"711427743","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasHfdsp_Gkdbs3_B4K-_5cN8Y0ZqJPVdm4MYXBzUoXs5QyNoPir8LEYK_RsMpQMxwI","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
'{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"500890765","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasBuRKr2vnMecj6ozdELAcZnUPL1FD3ojLSVrYrTckKy_pB2HekM693oJwKD0yH41Y","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
];

let resultAr = myAr.filter(function(element) {
if (element != '#' && element != null) {
console.log( element.match(/eng_tid":"(\d*)",/)[1]); // this logs what I want
return element.match(/eng_tid":"(\d*)",/)[1]; // this doesn't return what I want
} else {
return false;
}
});
console.log(resultAr);


How do I return what's output in the first console logger?

Answer Source

You should use 'map', instead of 'filter'.

let myAr = ['{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"100000077777226","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AauUajLpeWuhLBG3jk4ypnhABBcEcbN4M8Z2F6J_CQaQXEhPwL-3j1_dX5vhAleK3K7rjlzqJwnG4xGGaGdFk7Eb","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
    '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"711427743","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasHfdsp_Gkdbs3_B4K-_5cN8Y0ZqJPVdm4MYXBzUoXs5QyNoPir8LEYK_RsMpQMxwI","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
    '{"engagement":{"eng_type":"1","eng_src":"2","eng_tid":"500890765","eng_data":[]},"coeff2_registry_key":"0406","coeff2_info":"AasBuRKr2vnMecj6ozdELAcZnUPL1FD3ojLSVrYrTckKy_pB2HekM693oJwKD0yH41Y","coeff2_action":"1","coeff2_pv_signature":"1509941759"}',
    ];

let resultAr = myAr.map(function(element) {
    if (element != '#' && element != null) {
        return element.match(/eng_tid":"(\d*)",/)[1];
    } else {
        return false;
    }
});
console.log(resultAr);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download