Anu Anu - 1 month ago 6
Javascript Question

Returning index of an array based on mixture of values(integer,string) or (integer,float)

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

arraynum = ['10%','250','20%','500']
and user sends a value
15%
,in which range does this number resides? I could find index for a integer number using this code

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 mixture of integer and percentage value inside a array and number that a user pass to this function can be a integer,decimal or percentage How to find in which index does the given number resides? Should I convert all value in the mixture array to some format? How to do this? Can someone please help me with this? Thanks in advance.

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?