最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using If statement in Array.Filter - Stack Overflow

programmeradmin0浏览0评论

I am using Array.Filter as:

  this.newData = this.allData.filter(imp =>   
       imp.name.toLowerCase().includes(((filter.name) ? filter.name.toLowerCase() : imp.name.toLowerCase())) &&
       imp.type === ((filter.type) ? filter.type: imp.type) &&
       imp.createdBy.toLowerCase().includes(((filter.createdBy) ? filter.createdBy.toLowerCase() : imp.createdBy.toLowerCase()))
  )

But my imp.name can be null sometimes so the code errors out.

How can I add an if statement inside filter such that if any of the data is null dont add it to the AND.

Something like

if(imp.name!=null){
  imp.name.toLowerCase().includes(((filter.name) ? filter.name.toLowerCase() : imp.name.toLowerCase()))
}

Hope I am clear.

I am using Array.Filter as:

  this.newData = this.allData.filter(imp =>   
       imp.name.toLowerCase().includes(((filter.name) ? filter.name.toLowerCase() : imp.name.toLowerCase())) &&
       imp.type === ((filter.type) ? filter.type: imp.type) &&
       imp.createdBy.toLowerCase().includes(((filter.createdBy) ? filter.createdBy.toLowerCase() : imp.createdBy.toLowerCase()))
  )

But my imp.name can be null sometimes so the code errors out.

How can I add an if statement inside filter such that if any of the data is null dont add it to the AND.

Something like

if(imp.name!=null){
  imp.name.toLowerCase().includes(((filter.name) ? filter.name.toLowerCase() : imp.name.toLowerCase()))
}

Hope I am clear.

Share Improve this question edited May 22, 2019 at 14:30 aman asked May 22, 2019 at 14:08 amanaman 6,26217 gold badges64 silver badges118 bronze badges 5
  • can you paste data i.e. filter value and this.allData values? – JackOfAshes - Mohit Gawande Commented May 22, 2019 at 14:12
  • Use a normal function and return true or false as you need... – Heretic Monkey Commented May 22, 2019 at 14:16
  • @HereticMonkey I am filtering it out based on the entire conditions which is made up of 3 conditions as per my example. If I use individual if else and return true false how would the results bine. So basically this is the seach criteria. If filter selected matches the array then return filtered list else return all. – aman Commented May 22, 2019 at 14:22
  • So define a Boolean at the top that represents whether the item satisfies the filter. Set that the true or false depending on the various checks your doing. I'm assuming that if any one of the conditions is not met, it should not be included in the list? Just do var passedFilter = true; passedFilter = passedFilter && (condition1); passedFilter = passedFilter && (condition2);... etc. By basic Boolean logic, if any are false, it won't be included. – Heretic Monkey Commented May 22, 2019 at 14:26
  • See if statement checking for multiple boolean conditions for more ways of doing it. – Heretic Monkey Commented May 22, 2019 at 14:28
Add a ment  | 

3 Answers 3

Reset to default 3

If you want to check if a filter exists, and use it only if it exists, I'd do something like this:

items.filter(imp => {
      let keep = true;
      if (imp.name) {
        keep = keep && imp.toLowerCase().includes(filter.name ? filter.name.toLowerCase() : imp.name.toLowerCase());
      }
      if (imp.type) {
        keep = keep && imp.type === (filter.type ? filter.correctionType : imp.type);
      }
      if (imp.createdBy) {
        keep = keep && imp.createdBy.toLowerCase().includes(filter.createdBy? filter.createdBy.toLowerCase(): imp.createdBy.toLowerCase());
      }
      return keep;
    });

Personally I find this to be an example of overuse of ternaries. Took a while to figure out the logic and even then I think this does not solve the exact required filtering.

Filter is not shown here, so we can only guess.

this.newData = this.allData.filter(imp => {
    // Check if the properties we'll call methods on, are true-ty values.
    if ( !imp.name || !imp.createdBy ) return false;
    // imp.name.toLowerCase().includes( imp.name.toLowerCase()) is always true.
    // So the only way the name is invalid,
    // is if filter.name exists AND filter.name is not included inside imp.name.
    // So !filter.name gives us true if filter.name does not exist
    // and also makes sure filter.name exists before we try to use toLowerCase();
    const valid_name = !filter.name || imp.name.toLowerCase().includes( filter.name.toLowerCase());
    // Same here imp.type will always equal imp.type, so the ternary is redundant again.
    // The type will only be false if imp.type does not equal filter.correctionType
    const valid_type = !filter.type || imp.type === filter.correctionType;
    // Same again
    const valid_creation = !filter.createdBy || imp.createdBy.toLowerCase().includes( filter.createdBy.toLowerCase());
    // All 3 have to be true.
    return valid_name && valid_type && valid_creation;
});

To achieve expected result , use below option of using imp && imp.name in first line of filter

imp.name && imp.name.toLowerCase().includes(((filter.name)

Codepen - https://codepen.io/nagasai/pen/EzowXb?editors=1010

working code:

var allData = [{name: null , type: "A", createdBy: 'test1'},
              {name: 'aaaa' , type: "AB", createdBy: 'test12'},
              {name: 'bbbb' , type: "AA", createdBy: 'test13'},]

var filter = {name: 'bbbb' , correctionType: "AA", createdBy: 'test13'}

 var newData = allData.filter(imp =>   
       imp.name && imp.name.toLowerCase().includes(((filter.name) ? filter.name.toLowerCase() : imp.name.toLowerCase())) &&
       imp.type === ((filter.type) ? filter.correctionType : imp.type) &&
       imp.createdBy.toLowerCase().includes(((filter.createdBy) ? filter.createdBy.toLowerCase() : imp.createdBy.toLowerCase()))
  )
 
 console.log(newData)

发布评论

评论列表(0)

  1. 暂无评论