[Vuejs]-How to simplify array filter

1👍

if you really want to lower the repetition you could do something like this.

 items() {
  const lowerIncludes = (val) => val.toLowerCase().includes(this.table.filter.keyword)
  const fields = ['nombre', 'paisOrigen', 'ciudad', 'sector', 'contratadorPor', 'moneda']
  return this.table.filter.keyword ? this.dataArray.filter(item => fields.some(f => lowerIncludes(item[f]))) : this.dataArray
 }

you make the .toLowerCase().includes(this.table.filter.keyword) into it’s own function. then you list the fields you want to include in the or filter you’re using.

You then take fields.some(f => lowerIncludes(item[f]) to work like all of your || statements. If the keyword is in any of the fields, it will return true.

2👍

You can use the map function before applying the filter:

  1. Use map to convert values to lowercase (you can use for…in loop to
    transform all properties)
  2. Apply filter on the result of the map.
this.data.map(item => {
  let ret = {};
  for (let p in item) {
    ret[p] = item[p].toLowerCase();
  }
  return ret;
}).filter(item => {
  //... perform your filter logic here...
});

Leave a comment