最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter array by letter - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Sep 28, 2015 at 9:16 MateBoyMateBoy 4541 gold badge4 silver badges14 bronze badges 2
  • 1 you can use variable instead hard-coded A value – Grundy Commented Sep 28, 2015 at 9:18
  • You need to create a function for those cases and call it from inside of the filter. i.e return checkMyWord(indexOfLetter, letter, word); hope I made sense for you – Saar Commented Sep 28, 2015 at 9:20
Add a comment  | 

6 Answers 6

Reset to default 5

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;
}

A regexp will be more flexible I guess

var filteredNames = names.filter(function(word) {
    return /^A/.test(word);
});

A generic way to use it

function filterMatches(words, regexp) {
    return words.filter(function (word) {
         return regexp.test(word);
    });
}

filterMatches(words, /^A/); // for letter A, index 0
filterMatches(words, /^.{3}B/); // for letter B, index 4

why not create a function to do just what you want? From your code it be like this:

function filterName(arrayOfNames, index, letter) {
    var filteredNames = arrayOfNames.filter(function(word) {
     return word[index] === letter;
    });
    return filteredNames 
}

So you can just pass on the array, index and letter to it:

console.log(filterName(arrayOfNames, 3, 'x'));

You can create your own custom function

var array =["Anna", "Bob", "Charles", "Daniel", "Allison", "Beatrice", "Cindy", "Fiona"];
var matched_terms = [];
var search_term = "an";
search_term  = search_term.toLowerCase();
           array.forEach(item => {
                  if(item.toLowerCase().indexOf(search_term) !== -1 ){
                  console.log(item);
                  matched_terms.push( item ); 
      }

console.log(matched_terms);
})

Your filter function can be however complex you want, as long as it returns true for values to keep and false for values to skip. For example:

var filteredNames = names.filter(function(word) {
    return word.length > 3 && word[3] === "Y";
});

Even better, you can create the callback function dynamically since functions are first-class citizens in JS:

function createCallback(position, letter) {
  return function (word) {
    return word.length > position && word[position] === letter;
  }
}

var filteredNames = names.filter(createCallback(3, "Y"));

Higher-order functions like filter and map takes other functions as values which help them do their work. You can make this an even deeper redirection now by building an array of functions and them apply them all using the higher-order function reduce:

function createCallback(position, letter) {
  return function (word) {
    return word.length > position && word[position] === letter;
  }
}

function applyFilter(currentFilter, currentNames) {
  return currentNames.filter(currentFilter);
}

var filters = [
  createCallback(3, "Y"),
  createCallback(0, "A"),
  createCallback(2, "Y")
];

var ultraFilteredNames = filters.reduce(applyFilter, names);

I'm using react native

There I want to filter the array by letters like: - 'ar', 'd', etc.

so I used

 let data = this.state.staffData; // my array 

let output = text.toLowerCase(); // search input field data in lowercase

// Output:

let result = data.filter(fnd =>
  fnd.fname.toLowerCase().startsWith(`${output}`),
);
发布评论

评论列表(0)

  1. 暂无评论