Emily Chu
Emily Chu

Reputation: 187

Given an integer, search an array to return the two items the integer falls between in javascript

I have an array of game levels like this:

levels=[{points:0, level:One},{points:200, level:Two},{points:0, level:Three}..]

I have a points counter whose value changes as the game progresses i.e. counter=100. How do I search the array to find which items the counter value falls between and return the level values for both?

Upvotes: 2

Views: 70

Answers (2)

Chethan
Chethan

Reputation: 370

let levels=[{points:0, level:'One'},{points:200, level:'Two'},{points:400, level:'Three'}];
let counter = 210;
const filteredLevels = levels.filter(x=> counter >= x.points);
const maxPoint = Math.max.apply(Math, filteredLevels.map(p=> p.points));
var currentLevel = filteredLevels.find(y=> y.points === maxPoint); // result

console.log(currentLevel);

Gives the level in which the counter value falls

Upvotes: 0

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

You could use arrays filter method to search.

Example

let levels = [{ points: 0, level: 'One' }, { points: 200, level: 'Two' }, { points: 300, level: 'Three' }];

//Example 1
let userPoints = 150;
let searchLevel = levels.filter( value =>  userPoints >= value.points);
console.log("Example 1: ", searchLevel);

//Example 2
userPoints = 250;
searchLevel = levels.filter( value =>  userPoints >= value.points);
console.log("Example 2: ", searchLevel);

Upvotes: 1

Related Questions