简体   繁体   中英

typescript / javascript array.filter() with multiple conditions not returning expected values

I have cell definition with two properties:

class Cell {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

lets create new array who contains some cells:

let x : Cell[]=[new Cell(5,5),new Cell(5,9), new Cell(5,56)]

I would like to filter one cell (if exists in array, and return rest of the array):

x= x.filter(c=>(c.x!==5 && c.y!==5)

I`m expecting to get back array with 2 last cells, but it returns none of cells. It works fine if just one condition is used. Any solutions for multiple conditions?

You have the logic wrong. In order to match with Cell(5,5) you use

c => c.x === 5 && c.y === 5

But to filter it out you use the negative:

c => !(c.x === 5 && c.y === 5)

which is the same as

c => c.x !== 5 || c.y !== 5

Your Question was a little confusing I'm writing this based on my assumption.

You want to return the last two cells but that condition was contradictory as the last cells are having 5 as the value of x so you can check this condition to return the last two cells.

x= x.filter(c=>(c.x == 5 && c.y > 5))

In the second condition, I used greater than the operator to get the desired results.

If you found this incorrect let me know I will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM