Search code examples
javascriptarraysfunctionsortingcomparison-operators

Find index of number in array Javascript


I have got this issue where I want to return the index of the number in the array which is smaller the one before it. For eg. in this array [6, 8, 10, 2, 4], I want the function to return 3 (which is the index of 2 where 2 < 10). I have used a for loop to iterate over each number and compare it with index - 1 but am unable to output the correct answer. Below is my code:

// 1
function rotateNum(arr) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < arr[i - 1]) {
            return i;
        } else {
            return 0;
        }
    }
}

console.log(rotateNum([5, 4, 3, 1, 2]));
console.log(rotateNum([2, 3, 4, 5, 1]));
console.log(rotateNum([6, 8, 12, 1, 3]));
console.log(rotateNum([1, 2, 3, 4, 5]));

Please let me know where am I doing it wrong. Javascript.


Solution

  • It's very simple. First apply Math.min method and spread your array and easily get smallest number.Then you can find the index of smallest number in array by indexOf method. Here is the code:

    const rotateNum = array => {
        const small = Math.min(...array)
        return array.indexOf(small)
    }