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

202
Vistas
How can create a function like findSum([1,2,3,5], 5) that second param is the sum of to element of array and return those two element in javascript?

I wanna write a function that receive two parameter that first one is an array and the second is an integer; So I wanna return two element of the array that their sum be equal the second function's parameter. For example in this case findSum([1,2,3,5], 5) my function will return 2 and 3 that their sum being 5. I wrote a function but I think it can be better with another optimized coding.

function findSum(arr, sum){
  for(element of arr) {
    const first_element = element;
    for(innerElement of arr){
      if((innerElement !== first_element) && (innerElement + element === sum) )
          return {first_element, innerElement}
    }
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So, one clear issue with your code is that findSum([2,2,3],4) won't work, because of this line: if((innerElement !== first_element). You should check indexes, rather than values to avoid this.

Very quick example:

findSum = (arr, sum) => {
        return arr.map((x, i) => {
            return arr.map((y, j) => {
                if(i === j) return null;
                return x + y === sum ? {x, y} : null;
            }).filter(x => x);
        }).flat()[0];
    }

Essentially, what I''m doing is very similar to your original version, with some slight tweaks.

Rather than using two for loops like you, I use two maps to iterate over the array. This gives me access to the index (i & j).

If i === j then it's the exact same element (and not just the same value) so we can ignore it. This solves the if((innerElement !== first_element) issue.

Then I check to see if the sum is correct and return the values, or null if it's incorrect. Filtering this array with filter(x => x) returns only the truthy elements, i.e. removes the nulls so we are left with all the matches.

We then flatten the array and return the first object as that's all we need, but we could change that to return all the matches. findSum([2,2,1,3], 4) has two matches for example.

Key concepts: Array.map Array.filter Array.flat

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