1

I am trying to filter data based on input and it works fine but I want add an extra condition to it. It should return if titel or another value (for example sendFrom) is given.

 const newData = masterDataSource.filter(function (item) {

    const itemData = item.titel  ? item.titel.toUpperCase() : ''.toUpperCase();
    const textData = text.toUpperCase();
    return itemData.indexOf(textData) > -1;
  });

I tried adding some operators but it didn´t worked out as planed

     const newData = masterDataSource.filter(function (item) {

    const itemData = item.titel || item.sendFrom ? item.titel.toUpperCase() || item.sendFrom.toUpperCase() : ''.toUpperCase();
    const textData = text.toUpperCase();
    return itemData.indexOf(textData) > -1;
  });

thanks

2
  • What exactly did not work out? And what is uppercase of ""? Commented Nov 12, 2021 at 11:51
  • ''..toUpperCase() was unnecessary, sorry. I can still filter by titel but not by sendFrom Commented Nov 12, 2021 at 11:53

2 Answers 2

1

If I understand what you're after you would want something like:

const itemData = item.titel ? item.titel.toUpperCase() : (item.sendFrom ? item.sendFrom.toUpperCase() : ''.toUpperCase());

Parentheses are not required, but I added them to make it easier to get the logic.

Also, ''.toUpperCase() doesn't make much sense, it's the same as ''.

You could replace the initial condition with

const itemData = (item.titel  && item.titel.toUpperCase()) || '';

and the revised version:

const itemData = (item.titel  && item.titel.toUpperCase()) || (item.sendFrom  && item.sendFrom.toUpperCase()) || '';

Again, parentheses are not required.

References:
Conditional (ternary) operator
Logical Operators

Sign up to request clarification or add additional context in comments.

4 Comments

(item.titel && item.titel.toUpperCase()) || (item.sendFrom && item.sendFrom.toUpperCase()) || ''; can be shortened to (item.titel || item.sendFrom)?.toUpperCase() ?? ''
I think it should be (item.titel || item.sendFrom || '').toUpperCase() since if there's neither .titel nor .sendForm you call undefined.toUpperCase() which results in an error.
nope ... notice the usage of both operators, the Optional chaining ( ?. ) and the Nullish coalescing operator ( ?? ). One wants to exit es early as possible and does not want to have as a fallback variant an additional avoidable ''.toUpperCase()
Wow, you're perfectly right! I didn't even know that ?. existed and I'm using js for 15 years!
1

You could collect the wanted properties in an array and iterate them while checking the values.

const newData = masterDataSource.filter(({ titel = '', sendFrom = '' }) => 
    [titel, sendFrom].some(s => s.toUpperCase().includes(text.toUpperCase()))
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.