knox-flaneur
knox-flaneur

Reputation: 149

Boolean filters

I'm trying to write a function that gets rid of elements based on a parameter to look for. I'm not sure why this fails when given boolean expressions:

function getRid(array, discardThis) {
  if (array.length === 0) {
    return []
  }
  let newArr = array.filter( function (element) {
    if (element != discardThis) {
      return element;
    }
  })
  return (newArr.length === array.length) ? [] : newArr;
}

getRid([true, true, true, false, true], true);

Upvotes: 1

Views: 215

Answers (2)

synthet1c
synthet1c

Reputation: 6282

All you really need from your code is the following.

The filter did not work because it expected a Boolean for whether the item was to be kept, instead you gave it the value which in this case broke the filter.

note: a better name would be exclude

function getRid(array, discardThis) {
  return array.filter(function (element) {
    return element != discardThis
  })
}

console.log(
  getRid([true, true, true, false, true], true)
)
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53535

The filter function should return a boolean value, checking each element it will return true if it should be retained and false if it doesn't. Try:

function getRid(array, discardThis) {
  if (array.length === 0) {
    return []
  }
  let newArr = array.filter( function (element) {
      return element != discardThis
    }
  )
  // I'm not clear on this check so I left it, 
  // but it would make more sense to simply return newArr
  return (newArr.length === array.length) ? [] : newArr
}

Upvotes: 2

Related Questions