Push element from one array to another array

9

function that accepts a parameter and is a numeric array and it will cross the array and if the element is even it will push to the one "par" array and if it is odd it will push to the "odd" array

I tried to do it this way below but nothing worked. What would be the correct solution?

 function PickIt(array) {
  var array = [1, 2, 3, 4, 5];
  var par = [];
  var impar = [];

  for (var i = 0; i < array.length; i++) {
    if (array[i] % 2 === 0) {
      return par.push(array[i]);
    } else {
      return impar.push(array[i]);

    }
  }
}
PickIt();
    
asked by anonymous 29.08.2018 / 22:20

7 answers

7

I think there are some solutions I ended up implementing over your own code that was almost right, and I preferred to pass array per parameter and get the result right after execution, example?

function PickIt(array) 
{  
  var result = [];
 
  result['par'] = [];
  result['impar'] = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i] % 2 === 0) {
      result['par'].push(array[i]);
    } else {
      result['impar'].push(array[i]);
    }
  } 
  return result;
}
var array = [1, 2, 3, 4, 5];
var result = PickIt(array);
console.log(result['par']);
console.log(result['impar']);
    
29.08.2018 / 22:45
6

You can define your variables outside of the function if you want to use them later. You do not need to put as an array argument that is already defined.

     var array = [1, 2, 3, 4, 5];
     var par = [];
     var impar = [];
    
     function PickIt() {
      for (var i = 0; i < array.length; i++) {
        if (array[i] % 2 === 0) {
          par.push(array[i]);
        } else {
          impar.push(array[i]);
  
        }
      }
    }
    PickIt();
    console.log('par => ' + par);
    console.log('impar => ' + impar);
    
29.08.2018 / 22:45
5

On the first return (in the number 1 that is odd), it will exit the function returning only the number 1. The return ends the function by returning the value that was found. So you have to put it after you have processed what you wanted.

You should put a return at the end of the function (after the for loop) by returning the two arrays, for example, in object form, each with its name.

I think you want to pass the array as a parameter, so the array should be outside the function, not inside it.

To make your code simpler, you can use .filter with a ternary operator:

var array = [1, 2, 3, 4, 5];

function PickIt(array) {
  var par = [], impar = [];
  array.filter(i=>{ (i % 2 === 0 ? par : impar).push(i); });
  return {par, impar};
}

console.log(PickIt(array));       // a função retorna as duas arrays no mesmo objeto
console.log(PickIt(array).par);   // retorna apenas a array par[]
console.log(PickIt(array).impar); // retorna apenas a array impar[]

The object PickIt(array).par is an array with even numbers and PickIt(array).impar with odd numbers.

    
29.08.2018 / 22:33
1

As our friend Máttheus said, using forEach becomes more readable.

var array = [1, 2, 3, 4, 5];
 var par = [];
 var impar = [];

 function PickIt() {
  array.forEach(function(v,i) {   // v -> valor do array, i -> indice do array
    
    if(v % 2 == 0){               // Verifica os valores
      par.push(v);
    } else {
      impar.push(v);
    }
  })
}
PickIt();
console.log(par);
console.log(impar);
    
29.08.2018 / 23:17
1

I'm going to answer your question about which solution would be correct and without messing around with your code, its almost correct, you just did not ask to display the result on the screen, besides having mistakenly used the 'return'. >

I take the 'return' so that in the function call, after the first 'return', the execution does not exit the current subroutine and return to the point where it was called by stopping execution of 'for'. After finalizing 'for', I asked to print the odd and even arrays, using the 'console.log'. Through this, I can then visualize the result in the browser's developer tool.

function PickIt(array) {
  var array = [1, 2, 3, 4, 5];
  var par = [];
  var impar = [];

  for (var i = 0; i < array.length; i++) {
    if (array[i] % 2 === 0) {
       par.push(array[i]);
    } else {
       impar.push(array[i]);
    }
  }
  console.log(par);
  console.log(impar);
}
PickIt();
    
30.08.2018 / 13:22
1

Using Filter

Although the filter causes the execution to pass twice through the array, the code becomes simpler.

var array = [1, 2, 3, 4, 5];

function PickIt(arr) {
  return { 
    par: arr.filter(x => (x % 2 == 0)),
    impar: arr.filter(x => (x % 2 != 0))
  };
}

var result = PickIt(array);
console.log(result.par);
console.log(result.impar);
    
03.09.2018 / 13:55
0

Using the syntax for...of entered in ES6 you can do as follows:

const PickIt = elementos => {
  let pares = [];
  let impares = [];

  // Percorre cada item
  for (let elemento of elementos) {
    // Define a referência do array válido para este elemento
    let alvo = elemento % 2 === 0 ? pares: impares;

    // Adiciona o elemento
    alvo.push(elemento);
  }

  // Retorna o resultado nomeado
  return { pares, impares };
}

// Aqui vai a utilização
let array = [1, 2, 3, 4, 5];
let { pares, impares } = PickIt(array);

console.log('pares =>', pares.join(', '));
console.log('impares =>', impares.join(', '));

Remembering that the above solution is not compatible with all browsers and versions

  

for...of

     The for...of loop traverses iterative objects (including Array , Map , Set , arguments , and so on), invoking a custom function with instructions to execute for the value of each different object.

    
30.08.2018 / 13:44