Home > Mobile >  Sorting an array / table in JavaScript with keywords
Sorting an array / table in JavaScript with keywords

Time:11-30

I have a simple list and I am trying to create a search filter for this, you enter a keyword and it goes through the function and re-sorts this data list to show only ones that apply to the keyword

list: [
  {name: "Apple"},
  {name: "Grape"}
]

CodePudding user response:

Try Array.prototype.filter()

var list = [
  {name: "Apple"},
  {name: "Grape"}
];
var filtered = list.filter(function(o){
  return o.name == "Apple";
});

CodePudding user response:

ili is right, Array.prototype.filter() is the good way but it would be much better with a String.prototype.includes() too, because the current answer can only works if the person type exactly the good word. Here is an implementation more user-friendly :

list = [
  {name: "Apple"},
  {name: "Grape"}
]

input = "app"

filtered = list.filter(element => {
    if(element.name.toLowerCase().includes(input.toLowerCase())) {
        return element
    }
})

console.log(filtered)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related