Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

201
Vistas
Javascript: Why .map method returns undefined

I'm working on this problem in leetcode by using .map method, but somehow it returns undefined. Could anybody please explain why this happened? I read the doc, and it says that .map usually returns an array.

var twoSum = function (nums, target) {
    for (let i = 0; i < nums.length; i++){
        const num = nums[i];
        nums.slice(i+1).map((element) => {
            if (num + element === target){
                return [i, nums.indexOf(element, i+1)];
            }
        });
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Just to add , this is like a starter example where we can use two pointer pattern.

First setup to apply two pointer is to sort the array.

Then take two pointers first one starting at 0 index and second one starting at last index

Traverse the loop and check the target and increment and decrement the pointers accordingly

var twoSum = function(nums, target) {

  nums.sort((a,b) => a-b )
  
  var startingIndex = 0
  
  var lastIndex = nums.length-1;
  
   while(startingIndex<lastIndex){
     
     if(nums[startingIndex] + nums[lastIndex] === target){
       console.log(nums[startingIndex], nums[lastIndex])
       startingIndex++;
       lastIndex--;
     }
     
     if(nums[startingIndex] + nums[lastIndex] < target){
       startingIndex++;
     }
     
     if(nums[startingIndex] + nums[lastIndex] > target){
       lastIndex--;
     }
   }
  
  
};

console.log(twoSum([2, 7, 20, 13, 15], 33));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use Map here to achieve the result efficiently

var twoSum = function(nums, target) {
  const map = new Map();
  for (let i = 0; i < nums.length; ++i) {
    if (map.has(nums[i])) return [map.get(nums[i]), i];
    else map.set(target - nums[i], i);
  }
};

console.log(twoSum([2, 7, 11, 15], 9));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda