简体   繁体   中英

.filter() - example of how to use the val, arr and idx arguments properly?

I'm trying to determine how .filter() works.

I want to find those elements which match the regex provided, and build a newArray not of those elements, but of those elements which immediately follow them in the original array.

What is wrong with the below attempt?

function searchNames( logins ){
    var regex =/^\.|\.$/;
    var newArray = logins.filter(function(el,idx,arr){
        if (regex.test(el)) {
            console.log('desired return value is '+arr[idx+1]);
            return arr[idx + 1]; // but I get the original 'el' instead
        }
    });
    console.log(newArray);
}

searchNames([ "foo", "foo@bar.com", "bar", "bar@foo.com", ".foo", "food@bar.com" ]);

Are there no examples online of something like this? I sure can't find one.

You can't return the element you want in the new array from the callback. The filter method does expect a boolean result whether the current element should be in the result array. In your case, that would be

var newArray = logins.filter(function(el,idx,arr){
    return idx > 0 && regex.test(arr[idx-1]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM