Tips for streamlining the array filtering process

Is there a way to simplify the code to avoid repetitive use of lowercase and includes condition for each property?

 items() {
  return this.table.filter.keyword
    ? this.dataArray.filter(
        item =>
          item.nombre.toLowerCase().includes(this.table.filter.keyword) ||
          item.paisOrigen
            .toLowerCase()
            .includes(this.table.filter.keyword) ||
          item.ciudad.toLowerCase().includes(this.table.filter.keyword) ||
          item.sector.toLowerCase().includes(this.table.filter.keyword) ||
          item.contratadorPor
            .toLowerCase()
            .includes(this.table.filter.keyword) ||
          item.moneda.toLowerCase().includes(this.table.filter.keyword)
      )
    : this.dataArray;
}

Appreciate any help!

Answer №1

To optimize your code, you can first use the map function followed by the filter method:

  1. Utilize the map function to convert values to lowercase (you can utilize a for...in loop to transform all properties)
  2. Then apply the filter on the result of the map operation.
this.data.map(item => {
  let ret = {};
  for (let p in item) {
    ret[p] = item[p].toLowerCase();
  }
  return ret;
}).filter(item => {
  //... insert your filter logic here...
});

Answer №2

To reduce repetition, consider implementing the following approach:

 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
 }

Instead of repeating

.toLowerCase().includes(this.table.filter.keyword)
multiple times, encapsulate it within its own function. Define an array of fields that you want to include in the filter operation using or.

Modify

fields.some(f => lowerIncludes(item[f])
so that it functions like a series of logical OR statements. If the keyword is present in any of the specified fields, it will return true.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting the input tag id of an HTML form can be achieved by using the "id

<?php $i = 1; $query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page.""); while($result = mysql_fetch_array($query1)){ echo '<td colspan = "2">& ...

Mastering the Art of jQuery: Easily Choosing and Concealing a Div Element

I'm currently facing challenges in removing a div upon successful AJAX completion. The issue I'm encountering is that the word "Added" appears twice after success, indicating that I am not properly selecting the two divs containing it. Any sugges ...

What is the best way to preserve the status of a report when moving to a new component instance?

In my Vue application, I am using Vue version 3.1.31 and vue-router version 4.0.14. Within the application, there is a report consisting of multiple objects that can navigate to a new route where users can view or print a PDF of the information. However, ...

Why does the Vue i18n $t('hello') not function properly within a data property until the page is refreshed, yet it works fine when used in a normal template?

**Below are the components I require assistance with: The home component contains an array that needs to have its title and content translated, then binded as props to the info component. Since $t does not work with data method, how can I accomplish this u ...

Guide on how to initialize a variable in Express.js within a conditional statement in Node.js

Trying to create a variable based on a conditional statement, but even with simple code I am unable to retrieve the new variable. Here is my code: exports.productPatch = (req, res, next) => { const id = req.params.productId; const image = req.body.p ...

The added class is not being successfully applied to the ClassList

I'm currently working on a page where I want the colors of a button and the background to switch when the button is clicked. document.querySelector("body.light").classList.toggle("dark"); document.querySelector("button.dark").classList.toggle("light" ...

Trouble arises in Vuex when attempting to convert data into an observer

I have implemented Vuex to manage the state of my application. One issue I am facing is that when I dispatch an action to retrieve data from a server API and then commit a mutation, the data seems to be transformed into observer objects instead of remainin ...

Troubleshooting cross-origin resource sharing problem with Express NodeJS server running on localhost

Utilizing the fetch web API to send a POST request from ReactJS to an Express NodeJS server running on localhost with different ports. Using Client Fetch API fetch("http://localhost:8081/test", { method: "post", mode:"no-cors", headers: { ...

Discovering a method to establish a secure HTTPS REST API connection using an IP address, including the implementation of an SSL certificate

Can anyone help me figure out how to generate an SSL certificate for my IP address so that I can establish a secure connection between my frontend Vue and backend Express via the REST API? I am using NGINX as the web server to serve the frontend, which re ...

Creating a table from data in your database using Firebase

Can anyone guide me on how to craft a data table similar to this exampleusing information from a Firebase database like shown here The table should have columns for ID, Title, Number of Answers, Correct Answer, and Type. It would be best if this can be ac ...

JavaScript promises do not guarantee the execution of the loop

There was a block of Javascript code that I needed to modify. Initially, the code looked like this: if(!this.top3){ const promises = this.images.map((el, index) => { return this.getData(el.title, index); }); return Promise.all(promise ...

Is there a way to retrieve the information from the v-text-field without using the v-model directive?

<div v-for="i in parseInt(questionCount)" :key="i"> <v-layout> <v-flex xs6 offset-3 mt-15" > <label for=""> Enter question number {{index}}:</label> <v-text-fi ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...

The JSON data fails to load upon the initial page load

I am having trouble getting JSON data to display in JavaScript. Currently, the data only shows up after I refresh the page. Below is the code I am using: $(document).ready(function () { $.ajax({ url:"http://192.168.0.105/stratagic-json/pr ...

Firestore implementing batching for realtime updates with the onSnapshot 'IN' condition

Summary I'm currently working on developing a Chat List feature similar to those found in major social networks. However, I'm facing challenges with managing state in React Native due to a common issue with Firestore involving the use of onSnaps ...

Seeking an efficient method to quickly bring in the commonly utilized elements within a component?

Is there an efficient method for importing commonly used components? Every time I create a new component, I have to manually import and register each required component individually like this: import MyButton from './myButton' import MyInput fr ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

A comprehensive guide on iterating through an array in JavaScript

Currently, I am facing an issue while trying to iterate over an array of Objects in React that have been fetched from Django. The object is stored as an array, but when attempting to map it, I encounter a typeerror stating "cannot read property map of unde ...

Avoid form submission when the 'enter' key is pressed in Edge, but not in Chrome or Firefox

I'm dealing with an issue in HTML where a 'details' tag is set to open and close when the user presses enter. However, on Edge browser, pressing enter on the 'details' tag actually submits the form. I've been tasked with preve ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...