Home > Mobile >  How to return boolean value from filter method [closed]
How to return boolean value from filter method [closed]

Time:10-07

Searching an array for a value and returning true or false based on its presence.

Below is a working example of a filter method accessing the name property I care about:

  const renderNotDifferent = actions.filter(
    (action) => action.name !== "not-different"
  );

I want to create another property (boolean) if the action.name is === "should-be-different" - the two don't need to be combined, just including to show syntax.

Can anyone advise on the best approach?

CodePudding user response:

It doesn't have anything to do with filter - you can use map additionally:

const renderNotDifferent = actions.filter(
  action => action.name !== 'not-different' 
).map(
  action => ({ ...action, shouldBeDifferent: action.name === 'should-be-different' })
);

Alternatively, if you want to actually mutate the existing objects, you could use a regular for of loop:

for (const action of actions) {
  action.shouldBeDifferent = action.name === 'should-be-different'
}

UPDATE: Your question is a bit confusing. First it sounded like you want to add a property to each array element, but now with your edit I'm not sure anymore. In case you just want to have two booleans indicating whether any element has name not-different or should-be-different, respectively, then all you need it this:

const hasNotDifferent = actions.some(action => action.name === 'not-different')
const hasShouldBeDifferent = actions.some(action => action.name === 'should-be-different')

Another option, especially useful (and fast) in case there are more names you need to check for, would be to use a Set with all the different names:

const names = new Set(actions.map(action => action.name))

if (names.has('not-different')) {
  // render stuff
}

if (names.has('should-be-different')) {
  // render other stuff
}
  • Related