Ivan Vrzogic
Ivan Vrzogic

Reputation: 157

How to find if any of elements within an array are within range between 50 and 99 in JavaScript?

This is given array:

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

How to find if ANY of the elements from the array a are within range of 50 to 99? To return true if ANY of these elements are within range 50 to 99, and false if not!

How to find if ALL of the elements of this array a are within range of 50 to 99? To return true if ALL of these elements are within range 50 to 99 and false if at least one element is outside this range!

Upvotes: 2

Views: 774

Answers (4)

Farrukh Normuradov
Farrukh Normuradov

Reputation: 1194

You can you some and every.

const A = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

console.log('#1 ', A.some(element => element > 50 && element < 99))

console.log('#2 ', A.every(element => element > 50 && element < 99))

Upvotes: 0

Silidrone
Silidrone

Reputation: 1581

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

//if at least one element in the range of 50 and 99
console.log(a.filter(e => e >= 50 && e <= 99).length > 0)

//if all elements are in the range of 50 and 99
console.log(a.filter(e => e >= 50 && e <= 99).length === a.length)

Upvotes: 0

Aalexander
Aalexander

Reputation: 5004

You can use arrays functions some and every for this. In this solution I assumed that 50 and 99 are inclusive and they are also valid values.

How to find if ANY of the elements from the array a are within range of 50 to 99? To return true if ANY of these elements are within range 50 to 99, and false if not!

You can use .some()

a.some((x) => x >= 50 && x <= 99)

How to find if ALL of the elements of this array a are within range of 50 to 99? To return true if ALL of these elements are within range 50 to 99 and false if at least one element is outside this range!

You can use .every()

a.every((x) => x >= 50 && x <= 99)

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];


console.log(a.some((x) => x >= 50 && x <= 99));
console.log(a.every((x) => x >= 50 && x <= 99));

Here you can read more

Upvotes: 0

Thomas
Thomas

Reputation: 12637

Array#some() and Array#every()

var a = [2, 5, 8, 16, 35, 42, 55, 67, 89, 95, 102, 108, 112];

console.log("some", a.some(value => value > 50 && value < 99));
console.log("every", a.every(value => value > 50 && value < 99));

also check out the other array methods.

Upvotes: 2

Related Questions