• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

78
Views
ignore a object property while filtering is empty

I am trying to filter object array based on user selected value from drop down list

As you see in below example I want to filter the array based on chain and officeid. If one of them is empty then I want to skip that filter.

let list = [{
      "index": 4,
      "chain": "aaa",
      "officeId": "bbb"
    },
    {
      "index": 5,
      "chain": "ccc",
      "officeId": "ddd"
      
    }];

function search(chain, office) {
 let data = list.filter(function(result) {
      return result.chain === chain && result.officeId === office;
 });
 
 console.log(data);
}

search('aaa','bbb');  // this will work fine
search('aaa',''); // this returns empty array
search('', 'bbb'); // empty array

In above 3 statements I am expecting same output for all

If both are empty then it should skip the filter and return original array

i.e search('', ''); should not apply any filters

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

try using this instead, you just have to add one more condition

let list = [{
      "index": 4,
      "chain": "aaa",
      "officeId": "bbb"
    },
    {
      "index": 5,
      "chain": "ccc",
      "officeId": "ddd"
      
    }];

function search(chain, office) {
 let data = list.filter(function(result) {
      if( result.chain === chain && result.officeId === office){
         return result
      }
      if(!chain  && !office){
         return result;
      }
 });
 
 console.log(data);
}

search('aaa','bbb');  // this will work fine
search('aaa',''); // this returns empty array
search('', 'bbb'); // empty array
search("","");

You can also use a short hand like this

 let data = list.filter(function(result) {
      return (!chain && !office) || (result.chain === chain && result.officeId === office);
 });
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error