Home > database >  Find index of number in array Javascript
Find index of number in array Javascript

Time:03-16

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.

CodePudding user response:

function rotateNum(arr) {
  const minVal = Math.min(...arr);
  const index = arr.findIndex(v => v === minVal);
  return index;
}

here, first i found out min value of an array and then using array findIndex method we got the index

CodePudding user response:

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)
}

CodePudding user response:

here you go mate:

function rotateNum(arr) {
  for (x in arr) {
  arr[x] < arr[x - 1] ? console.log(arr.indexOf(arr[x - 1])) : {};
 }}
  • Related