Push element from one array to another array

Asked

Viewed 1,322 times

9

function that accepts a parameter and is a numerical matrix and will cross the array and if the element is even will push to the an array "even" and if it is odd will push to the array "odd"

I tried to do it this way below but nothing worked. What would be the right 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();
  • 1

    I’m surprised no one suggested using the foreach. It gets so simple and readable.

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

7 answers

6

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

You must place a Return at the end of the function (after the loop for) returning the two arrays, for example, in object form, each with its own name.

It seems to me that 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 the PickIt(array).impar with the odd numbers.

  • 1

    Vc creates a function with a parameter (array) and in the function call you do not pass this parameter !

  • I had not even noticed rs

  • I thought !! I liked your solution now +1 :)

  • Obg man! Your too good. Thanks!

6

You can set your variables outside the function if you want to use them later. Vc does not need to put as argument array 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);

6

I believe that there are some solutions I ended up implementing on top of their own code that was almost right, and I preferred to pass the array by parameter and have 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`]);

2

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

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

1

I answer your question about which solution would be correct and without fiddling too much in your code, yours is almost correct, you just did not ask to display the result on the screen besides having mistakenly used the 'Return'.

I took the 'Return' so that in the function call, after the first 'Return', the execution does not leave the current subroutine and returns to the point where it was called stopping the execution of 'for'. After finishing the 'for', I asked to print the even and odd arrays, using the 'console.log'. Through this, I can then view the result in the browser 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();

1

Using the syntax for...of introduced into the ES6 you can do it this way:

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 loop for...of traverses iterative objects (including Array, Map, Set, the object arguments and so on), calling a custom function with instructions to be executed for the value of each distinct object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.