Kristina Bressler
Kristina Bressler

Reputation: 1722

How to find first element that's less than the x in an array in Javascript?

I have this question in which I wanted to loop through an array starting from large number to smaller number and compare the number in the array against the x provided.

My code was supposed to be like this:

function convertToRoman(num) {

  var decimalNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

  while (num > 0){ // to prevent the number from reaching zero
    for (var k = 0; k < decimalNum.length; k++) { //to loop through the array

    if(num > decimalNum[k]) {return k}; //this is the part in which I wanted to return the element that is next in the array that is less than the num
    }
  }


}

convertToRoman(36);

For example, if the num = 36, then the next number in the array that is less than 36 would be 10. So I wanted to return 10. How do I do that?

I tried to find solutions online but the only solutions I found was for Java or C++ which is completely different from JavaScript, correct? And I don't think that binary search should be used as well...

Upvotes: 1

Views: 4627

Answers (3)

Jayme
Jayme

Reputation: 1946

Return the value not the index you are on:

function convertToRoman(pNumber) {

      var array = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
     
        for (var i = 0; i < array.length; i++) {
            if (pNumber > array[i]) {//if the current item is smaller than the parameter
                return array[i]; //return the value at the index you are on
            }; 
         } 
    }
    
    console.log(convertToRoman(36));//returns 10

When you get to a item that is smaller, then return that item

Upvotes: 1

Lennholm
Lennholm

Reputation: 7460

Here's a solution that will work in IE and regardless of how the values in the array are sorted

var lesser = decimalNum.filter(function(dec) {
  return dec < num;
});
var result = Math.max.apply(null, lesser);

If you know that the decimalNum array is alwys sorted the way it is in your code, you can simply replace the Math.max part with lesser[0]

Upvotes: 0

Viplock
Viplock

Reputation: 3319

for that you should get the value not index

function convertToRoman(num) {

  var decimalNum = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];

   //   while (num > 0) { // to prevent the number from reaching zero
    for (var k = 0; k < decimalNum.length; k++) { //to loop through the array

      if (num > decimalNum[k]) {
        return decimalNum[k]
      }; //this is the part in which I wanted to return the element that is next in the array that is less than the num
     }
//  }
}

console.log(convertToRoman(36));

Upvotes: 0

Related Questions