divide an array by numerical indexes

0

I want the 2.4.6 indexes that refer to Asian countries to be stored in their respective array, and the rest in the other array

mix = ['nulla' , 'italia', 'cina', 'germany', 'india', 'france', 'japan']  
europa = []
asia = []

with the following operation I receive only an undefined error

mix.map(function(indice){ if(indice % 2 == 0) {asia.push(indice)}}) // undefined

with my previous code I did not have any problem

 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers.map(function(x){if(x % 2 == 0) {pares.push(x)}})

/*
undefined
[2, 4, 6, 8, 10] ] */

numbers.map(function(x){if(x % 2 == 1) {dispares.push(x)}}) // undefined [1, 3, 5, 7, 9]

although I did not understand why I returned undefined

    
asked by steven 27.04.2017 в 18:54
source

1 answer

1

One way to see arr.map(a,b) is to consider that the first argument a is the element of the matrix arr , the index, b , would be the second argument.

In Array.protoype.map () we talk about three arguments, the element and the index and the matrix in the example included above a , b and arr respectively.

Example:

var mix = ['nulla' , 'italia', 'cina', 'germany', 'india', 'france', 'japan']  
var asia =[];
mix.map(function(elemento,indice){
  if (indice % 2 == 0) asia.push(elemento);
});
document.write(asia);

With regard to

mix = ['nulla' , 'italia', 'cina', 'germany', 'india', 'france', 'japan'];
mix.map(function(indice){ if(indice % 2 == 0) {asia.push(indice)}})

Returns undefined for each of the elements in the array, because the first argument takes the one element of the a matrix in each iteration, for example, 'nulla' % 2 == 0 returns false , as the if does not include the statement else does nothing, in other words assigns undefined to the resulting matrix, and so on for each element.

    
answered by 27.04.2017 / 20:41
source