Search code examples
javascriptvue.jslodash

Filter using lodash


I want to add element to array if there is no element with the same type and format. I did it with for loop, but it looks bad.

for (i = 0; i < this.model.array.length; i++) {
      const selectedElement = this.model.array[ i ]
      if (selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type) {
        this.model.array.splice(i, 1)
        this.model.array.push(item)
        break
      }
      if (i === this.model.array.length - 1) {
        this.model.array.push(item)
      }
    }

Could you tell me how can I do this lodash filter? I tried something like this:

let filter = _.filter(this.model.array, function (o) {
      return ((o.value.type !== item.value.type) && (o.value.format !== item.value.format)) })

but it does not work, it returns 0 array every time. My idea was to filter these elements (but it's just one) which type and format is the same as items and then push something using this filtered array. Or maybe there is another way how can I add elements if condition is met?

Item looks like this: enter image description here


Solution

  • You have the wrong boolean operation in your filter.

    Consider your original condition to find matching entries in a loop:

    selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type
    

    Let's call the two tests (or "predicates") A and B, such that the expression reduces to:

    A && B
    

    Within your filter call you want to retain the entries that do not match, i.e.:

    !(A && B)
    

    which De Morgan's Laws say is equivalent to:

    !A || !B
    

    However what you've actually written is:

    !A && !B
    

    which is equivalent to:

    !(A || B)