tibco
tibco

Reputation: 9

User Array.filter with multiple condition

I am using array.filter to filter the following array

let array =   [[75, -5750, 115],
 [76, -5750, 115],
 [93, -5750, 115],
 [94, -5750, 115],
 [95, -5750, 115],
 [96, -5750, 115],
 [97, -5750, 115],
 [98, -5750, 115],
 [99, -5750, 115]]

var lucky = array.filter(a=>a[0]>75); //this works
console.log(lucky);

I want to achieve something like

var lucky = array.filter(a=>98>a[0]>75); //apply two condition //it returns whole array in this case

How to achieve this ???

Upvotes: 0

Views: 128

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

**You need to use logical operator to combine two conditions

When you want all the conditions to be must than you use & AND operator.

When you want consitons to be optional than you use | OR operator.

let array =   [[75, -5750, 115],
 [76, -5750, 115],
 [93, -5750, 115],
 [94, -5750, 115],
 [95, -5750, 115],
 [96, -5750, 115],
 [97, -5750, 115],
 [98, -5750, 115],
 [99, -5750, 115]]

var lucky = array.filter(a=>a[0]>75 && a[0]<98); //this works
console.log(lucky);

Upvotes: 1

Sebastian Speitel
Sebastian Speitel

Reputation: 7346

Just use && to only return true if 2 conditions are met

let array = [
  [75, -5750, 115],
  [76, -5750, 115],
  [93, -5750, 115],
  [94, -5750, 115],
  [95, -5750, 115],
  [96, -5750, 115],
  [97, -5750, 115],
  [98, -5750, 115],
  [99, -5750, 115]
]

var lucky = array.filter(a => a[0] > 75 && a[0] < 98);
console.log(lucky);

.filter() takes a function as an argument. In this case that would be the same as

function(element){
  return element[0] > 75 && element[0] < 98;
}

Upvotes: 1

mchandleraz
mchandleraz

Reputation: 381

Seems like what you want is the logical and operator. Something like this:

array.filter(a => 98 > a[0] && a[0] > 75);

Upvotes: 2

Related Questions