Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!