Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda