Home > Net >  Javascript - filter if statement doesnt work
Javascript - filter if statement doesnt work

Time:08-05

Hey guys i got this code where i wanted filter array and return only if doesnt equal to type RJ_TIME and seatClassKey TRAIN_1ST_CLASS at same time.

This doesnt work and behave like OR, so it will return me object that isnt RJ_TIME or TRAIN_1ST_CLASS.

.filter((pClass) => { 
  if (isFirstClassSoldOut) {
    if (pClass.type !== "RJ_TIME" && pClass.seatClassKey !== "TRAIN_1ST_CLASS") {     
      return pClass  
    }
  } else {
    return pClass
  }
})
.map((pClass) => (

CodePudding user response:

The condition in the callback for filter needs return a boolean value which is what filter uses to determine whether the iterated element is returned or not.

Here only objects 2 & 4 will be returned as they're the only objects whose properties match the condition.

const isFirstClassSoldOut = true;

const arr = [
  { type: 'RJ_TIME', seatClassKey: 'TRAIN_1ST_CLASS' },
  { type: 'RJ_TIME2', seatClassKey: 'TRAIN_1ST_CLASS2' },
  { type: 'RJ_TIME3', seatClassKey: 'TRAIN_1ST_CLASS' },
  { type: 'RJ_TIME4', seatClassKey: 'TRAIN_1ST_CLASS4' },
];

arr.filter(pClass => { 
  return isFirstClassSoldOut
    && (pClass.type !== 'RJ_TIME'
      && pClass.seatClassKey !== 'TRAIN_1ST_CLASS');
})
.map(pClass => console.log(pClass));

  • Related