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

164
Vistas
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
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