Home > OS >  Using odd index to return odd numbers JavaScript
Using odd index to return odd numbers JavaScript

Time:09-16

I'm trying to solve a problem on a testing website and I'm getting confused on trying to find the odd numbers from a passed in array at odd index.

Code I have so far;

    function codeNation(arr) {
    let newArr = [];
    arr.forEach(function(value) {
      if (value % 2 !== 0) {
        newArr.push(value);
      }
    });
    return newArr;
  }
  
  console.log(codeNation([1, 3, 5, 7, 9, 11]));

In the above example I want it to return [3, 7, 11] but I can't figure out how. Can you please fix my code and explain to me the best way of getting an odd number at an odd index from a passed in array to the function? The order of the numbers has to be retained.

CodePudding user response:

  • So what you are doing wrong here is that you are not checking the index. that's why you are not getting desired output.
  • To solve your problem what I did is that I used Array's filter method and then first check if the index is odd or not, if it's odd then I am checking whether the value is odd or not is its odd then we return the value.
    function codeNation(arr) {
      const result = arr.filter((value, i) => {
        if (i % 2 != 0) {
          if (value % 2 != 0) {
            return value;
          }
        }
      })
      return result;
    }
    
    console.log(codeNation([1, 3, 5, 7, 9, 11]));

CodePudding user response:

Уou need to use an index to determine if it is odd or not. But you can also reduce the amount of code and increase readability if use .filter

const isOdd = (num) => Boolean(num % 2);
const odds = (arr) => arr.filter((value, index) => isOdd(value) && isOdd(index));

console.log(odds([1, 3, 5, 7, 9, 11]));
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

we can make this way too

filter will give itself true values only we no need to check values if or else

const oddIndexValues =(ar)=>{
const getValues = ar.filter((e, i)=> i%2 && e%2)
return getValues
}
console.log(oddIndexValues([1, 3, 5, 7, 9, 11]))

  • Related