Home > Mobile >  Divide array into two arrays odd and even
Divide array into two arrays odd and even

Time:10-22

This is the code but it returns in unidentified . It should return two arrays where the first one is a set of odd numbers in the original array and the second is odd

function evenAndOdd(array) {
    let odd = [];
    let even = [];
    for (i = 0; i < array.length; i  ) {
        if (array[i] % 2 === 0) {
            even.push(array[i]);
        } else {
            odd.push(array[i]);
        }
    }
    return even,odd;
}

CodePudding user response:

adding curly braces around your return values converts them into accessible objects

function evenAndOdd(array) {
    let odd = [];
    let even = [];
    for (i = 0; i < array.length; i  ) {
        if (array[i] % 2 === 0) {
            even.push(array[i]);
        } else {
            odd.push(array[i]);
        }
    }
    return {even,odd};
}


console.log(evenAndOdd([1,2,3]))

CodePudding user response:

You cant return two separate values from the same function. Instead, you can return a new array containing both of the other arrays.

function evenAndOdd(array){
  let odd = [];
  let even = [];
  for (i=0; i<array.length; i  ){
    if (array[i] %2===0){
      even.push(array[i]);
    }else{
      odd.push(array[i]);
    }
  }
  return [even,odd];
}

CodePudding user response:

If you're returning two or more variables, you can return them inside an array such as:

function evenAndOdd(array) {
  let odd = [];
  let even = [];
  for (i = 0; i < array.length; i  ) {
    if (array[i] % 2 === 0) {
      even.push(array[i]);
    } else {
      odd.push(array[i]);
    }
  }
  return [even, odd];
}

console.log(evenAndOdd([1,2,3,4,5,6]));

CodePudding user response:

function evenAndOdd(array) {
    let odd = [];
    let even = [];
    for (i = 0; i < array.length; i  ) {
        if (array[i] % 2 === 0) {
            even.push(array[i]);
        } else {
            odd.push(array[i]);
        }
    }

    return [even, odd];
}

var [even, odd] = evenAndOdd([0,1,2,3,4,5,6,7,8,9])
console.log("Even "   even)
console.log("Odd "   odd)

CodePudding user response:

  • You have to pass a valid number array.
  • and all I have done is just created an object with odd and even values array and return it because your code was only returning odd numbers.

function evenAndOdd(array) {
  let odd = [];
  let even = [];
  let length = array.length
  for (i = 0; i < length; i  ) {
    if (array[i] % 2 === 0) {
      even.push(array[i]);
    } else {
      odd.push(array[i]);
    }
  }
  return {
    odd,
    even
  };
}

console.log(evenAndOdd([1, 2, 3, 4, 5, 6, 7, 8, 9]))

CodePudding user response:

arr[i] & 1 === 0 is more elegant and should run more quickly than arr[i] % 2 === 0 if you're working with a large array

  • Related