Anu - 8 months ago 30

Javascript Question

Hi I am trying to find a index for a number in percentage and integer array. Say

`arraynum = ['10%','250','20%','500']`

`15%`

`function test(number, ranges) {`

for (var i = 0; i < ranges.length; ++i) {

if (number < ranges[i]) {

return i;

}

}

}

var ranges = [2000, 4000, 6000, 999999];

console.log(test(1710, ranges));

Now I have

Answer

Checking condition for mixture of values with one single input is little tricky and you need to go for **JSON array**.
Please run

```
var array_of_elements = [{
"Price": 250,
"Percentage": "10"
}, {
"Price": 500,
"Percentage": "25"
}, {
"Price": 750,
"Percentage": "50"
}, {
"Price": 1000,
"Percentage": "75"
}];
function test(number_or_percent, array) {
for (var i = 0; i < array.length; ++i) {
if (number_or_percent.charAt(number_or_percent.length - 1) == "%") {
if (parseInt(array[i].Percentage) > parseInt(number_or_percent.slice(0, ((number_or_percent.length) - 1)))) {
return i;
}
} else {
if (array[i].Price > parseInt(number_or_percent)) {
return i;
}
}
}
}
console.log(test('100', array_of_elements));
console.log(test('30%', array_of_elements));
```

**Is this what you want?**

Source (Stackoverflow)