How to use return values using . map() in Javascript

Asked

Viewed 230 times

0

I’m trying to make a way .map(), but I’m not getting it. My last code was this:

var double = x => x * 2;

function filtro(funcao, numeros) {
	let arr = [];
  
  for (let i = 0; i < numeros.length; i++){
  	arr.push(numeros[i](funcao));
   }
   return arr;
}
  		


console.log(filtro(double, [1, 2, 3, 4, 5, 6, 7, 8, 10]));

It would have to return: 2,4,6,4,10. etc...

Someone can help me ?

  • The code is losing its temper, I’ve already edited twice.

  • @wmsouza Fala mano, boa noite. É não, ali ele usa o map do javascript, no meu código no caso, I’m creating the map, got it ?

1 answer

1


The way the code is, just call the method passing as parameter numeros[i] see that i is the index of each element.

var numeros = [1, 2, 3, 4, 5, 6, 7, 8, 10];
var i = 4; // Índice

// Saida => 5
console.log(numeros[i]);

i = 2; // Índice

// Saida => 3
console.log(numeros[i]);


i = 6; // Índice

// Saida => 7
console.log(numeros[i]);

See working

var double = (x) => x * 2;

function filtro(funcao, numeros) {
  let arr = [];
  for (let i = 0; i < numeros.length; i++){
    arr.push(funcao(numeros[i]));
  }
  return arr;
}

console.log( filtro(double, [1, 2, 3, 4, 5, 6, 7, 8, 10]) );

  • Damn, man, thank you so much. I had made exactly this code, what went unnoticed was the parameters, instead of ta (function, numbers), tava (numbers, function).

Browser other questions tagged

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