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

162
Views
JS: Given an array, find element pairs whose sum equal the target value

Yes, as the title suggests

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

What I have done so far

function pairwise(arr, arg) {
  if (arr.length === 0) return 0
  let res = [];
  let indexes = [];
  let indexArr = []
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arg === arr[i] + arr[j] && !indexes.includes(i) && !indexes.includes(j)) {
        res.push([arr[i], arr[j]]);
        indexes.push(i);
        indexes.push(j);
      }
    }
  }
  console.log(res)
 
  for (let i = 0; i < res.length; i++) {
    for (let j = 0; j < res[i].length; j++) {
      indexArr.push(arr.indexOf(res[i][j]))
    }

  }

  return indexArr.reduce((curr, prev) => curr + prev)
}

pairwise([1, 1, 1], 2);

I am doing this in Freecodecamp. It passes some test but fails the following tests:

pairwise([1, 1, 1], 2) should return 1. (above code returns 0) pairwise([0, 0, 0, 0, 1, 1], 1) should return 10. (above code returns 8)

I think I am doing wrong in the indexOf part. How to solve this?

about 4 years ago · Juan Pablo Isaza
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!