Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda