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

What is the trick to ensuring that the bind submit function always works consistently instead of sporadically?

I am attempting to compare two values (min - max) from two input fields. If the min value is greater than the max value, an alert message should be displayed... The issue arises when I correct the max value and submit again, as it continues to show the sa ...

AngularJS is patiently anticipating the population of the scope for ng-show

I have implemented ng-show to display an error message based on an array. The code I used is ng-show="!items.length". However, since the items are populated after a request, there is a flickering effect for a brief moment before the items are loaded. Is th ...

PhpStorm flawlessly detects ES7 type hinting errors

For my project, I have implemented TypeScript. While JavaScript's array includes() function has been valid since ECMA6, setting the lib parameter in tsconfig to "es6" results in a non-fatal error being thrown in the browser console when using the foll ...

When setValue is called on VCheckbox in Vuetify, it emits an event called "update:modelValue"

After setting a value for the checkbox, I encountered a warning message: [Vue warn]: Component emitted event "update:modelValue" but it is neither declared in the emits option nor as an "onUpdate:modelValue" prop. Example.vue <script setup lang="t ...

Having trouble with npm? It's showing a "Response timeout" error when attempting to fetch data from https://registry.npmjs

Whenever I attempt to install a package, I encounter the following error message. I've exhausted all my options, can someone please assist me? npm ERR! Response timeout occurred when attempting to fetch https://registry.npmjs.org/base-config-proc ...

Managing Vue StateWhether you're using Vuex or the

Is it possible to maintain the state of a Vue component so that when returning to it, the previous state is preserved? For instance: 1) I am on Page A, perform a search, results are displayed, I scroll down and select item 34. 2) Next, Page B opens with ...

Using Jquery to show element when <select> is updated

I've been struggling to make this work due to my limited jquery/js skills. My goal is to have a different message displayed for each option selected from the dropdown menu for further information. <label class="checklabel">Is it possible to re ...

What is the process for submitting data using AJAX in Django?

I am facing an issue with my dynamically updating form. When I submit the form, I want to post the data to a views function and receive a response. Below is the code from my template file: $("#myForm").submit(function(){ event.preventDefault(); va ...

Obtain the inner HTML of a component and store it as a variable in Vue.js 2

Imagine I have a vuejs component named child-component that is inserted into a parent component in the following manner. <child-component> <div>Hello</div> </child-component> Please note, this does not represent the template of ...

Unable to add items to the global JavaScript array variable

My goal is to populate a global array variable within my ready function, but when I attempt to access the data later on, the array appears to be empty. This is how my ready function looks: var counter = 0; var services = []; var names = [] va ...

Leveraging .tsx components within nested .tsx components in React Native

Currently, I am delving into the world of building apps using TypeScript in React Native. Coming from a background as a Swift developer, adjusting to JavaScript and TypeScript has been an interesting journey. An observation that stood out to me is the cha ...

Can the Flash Configurator be converted to PHP or Javascript?

Considering converting this flash application into either PHP or JavaScript. Take a look at the example: In PHP, the page reloads every time the customer selects a color. With AJAX, it's challenging to pass the selected value to PHP. Are there any ...

Having trouble with your HTML5 canvas?

Below is the JS code snippet: function DisplayText(output, x, y){ var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillText ("A" , x, y); ctx.font = 'bold 20px sans-serif'; ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

I'm looking to create a JavaScript function that will extract each element from a div and then apply a corresponding CSS block to activate it

My goal was to create this function using Flask, but it seems that only JavaScript is capable of achieving it. This is my first attempt at coding it. Here's the code snippet: const navSlide2 = () => { const burger = document.querySelector(&apos ...

The Chrome developer tools are unable to locate the HttpRequest

While working in Python, I am utilizing the requests library to make a POST request to a specific URL. However, upon clicking the button, it seems that nothing is happening as per Chrome Developer Tools. No XHR requests are being made and no data is being ...

Implementing a language switch feature for text display in Node.js and Next.js websites

One of the features my client is requesting for a web app is dual language support, where users can easily switch between French and English. To address this requirement, I incorporated a button that toggles a state and saves the user's language pref ...

What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code: export const ProductsByFilter = async (req, res) => { const {a, b, c} = req.query let query = {} if (a) { query.a = a; } if (b) { query.b = b; } if (c) { ...

Combining two 2D numpy arrays

I am attempting to combine two 2D numpy arrays using the np.concatenate function. Here is my code: import numpy as np arr = np.array([[]]) #initialize empty 2D array a = np.array([[0.0012, 0.032, 0.039, 0.324]]) b = np.array([[1, 0.2, 0.03039, 0.1324]]) ...

The element div is not permitted as a child of the element h5 in this particular scenario

My code snippet is as follows: $compile .= "<h5 data-count='".$acctemmpi. "' class='shortcode_accordion_item_title expanded_". $expanded_state . "'>" . $title . "<div class='ico'&g ...