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

146
Views
Checking for duplicates within an array

I am trying to check for matching instances of arrays within a larger array. To do this, I am implementing a condition where if two of three numbers in an array match two of the three members of any of the arrays within a larger array, there is a continue statement to go back to a previous loop:

var threeSum = function (nums) {
  let result = [];
  for (let i = 0; i < nums.length - 2; i++) {
    for (let j = i + 1; j < nums.length - 1; j++) {
      loop1: for (let k = j + 1; k < nums.length; k++) {
        if (nums[i] + nums[j] + nums[k] === 0) {
          let smallArray = [nums[i], nums[j], nums[k]].sort((a, b) => a - b);
          for (let l = 0; l < smallArray.length && result[l]; l++) {
            if (
              smallArray[0] == result[l][0] &&
              smallArray[1] == result[l][2]
            ) {
              console.log("we already have this array")
              continue loop1;
            }
          }
          result.push(smallArray);
        }
      }
    }
  }
  return result;
};

Thus, for example threeSum([-1, 0, 1, 2, -1, -4]) should return [[-1, 0, 1], [-1, -1, 2]] when is instead is returning [[-1, 0, 1], [-1, -1, 2], [-1, 0, 1]]. I have checked using the console.log in the inner most conditional, and the if statement is never returning as true, so it is never entering the continue command. But the first and third arrays should meet the requirements of this, so it seems as if when checking the third array, the function should kick back the command.

I am a bit puzzled as to what is going wrong.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

A single loop approach but with recursion and filtering for arrays with same values.

function threeSum(array, temp = [], sum = 0, i = 0) {
    if (temp.length === 3) return sum ? [] : [temp];

    const result = [];
    
    while (i < array.length) {
        result.push(...threeSum(array, [...temp, array[i]], sum + array[i], ++i));
    }

    return result.filter((s => a => (b => !s.has(b) && s.add(b))([...a].sort().join('|')))(new Set));
}

console.log(threeSum([-1, 0, 1, 2, -1, -4]));

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!