Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  8] [ 5]  / answers: 1 / hits: 27913  / 9 Years ago, mon, september 28, 2015, 12:00:00

Pardon me if this has been asked but I searched and didn't find the specific implementation of my problem.



Anyway, I'm currently learning high-order functions in JavaScript and I'm at the array.prototype.filter function. I understand its purpose (as its name so conveniently implies) but I'm having trouble implementing this:



So, say I have an array of names, like this:



var names = [Anna, Bob, Charles, Daniel,
Allison, Beatrice, Cindy, Fiona];


And then I want to, say, filter that array by all entries that start with the letter A. I'm aware of the fact that I could do this:



var filteredNames = names.filter(function(word) {
return word[0] === A;
});


And that would work just fine. But say I want to be less explicit and make it more adaptable to more situations. Say I want to program the filtering so that I can say return only the entries that have the letter x at index [y], for example return only the entries that have the letter F at index[3].



How can I achieve that?


More From » arrays

 Answers
7

You can define your own filter function :



function filter(names, index, letter) {
var filteredNames = names.filter(function(word) {
return word.charAt(index) === letter;
});
return filteredNames;
}

[#64915] Thursday, September 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
colby

Total Points: 311
Total Questions: 102
Total Answers: 102

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;