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

253
Visualizações
Is there a way to make this Javascript code more efficient?

It is a simple exercise that I am doing for mere practice and leisure, I have done it in various ways but I was wondering if there is an even more practical way or to reduce the lines of code making use of the many methods of JavaScript.

The exercise is about receiving an array (arr) and a number (target) and returning another array with a pair of numbers found in 'arr' whose sum is equal to 'target'.

function targetSum3(arr, target) {
            let newArr = [];
            let copyArray = arr;
            for (let i of copyArray) {
                let x = Math.abs(i - target);
                copyArray.pop(copyArray[i]);
                if (copyArray.includes(x) && (copyArray.indexOf(x) != copyArray.indexOf(i))) {
                    newArr.push(i);
                    newArr.push(x);
                    return newArr;

                }
            }
            return newArr;
        }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If you are fine with a function that just returns a pair of numbers (the first match so to speak) whose sum equals the targets value, this might be enough:

function sumPair (arr, target) {
    while(arr.length) {
        let sum1 = arr.shift();
        let sum2 = arr.find(val => sum1 + val === target);
        if (sum2) return [sum2, sum1];
    }
    return null;
}

about 4 years ago · Juan Pablo Isaza Relatório

0

const targetSum = (arr, target) => {
    const first = arr.find((v,i,a) => arr.includes(target-v) && (arr.indexOf(target-v) !== i));
    return first ? [first, target - first] : null;
};
    
const values = [1,2,3,4,5,6,7,8,9];
console.log(targetSum(values, 1)); // null
console.log(targetSum(values, 2)); // null
console.log(targetSum(values, 3)); // [1, 2]
console.log(targetSum(values, 15)); // [6, 9]
console.log(targetSum(values, 20)); // null
about 4 years ago · Juan Pablo Isaza Relatório

0

I changed for loop with forEach (more efficient) and there is no need for the copyArray array so I removed it. I also changed pop() with shift(), I think you want to shift the array and not pop-it (if I understand the task correctly).

function targetSum3(arr, target) {
        let newArr = [];
        arr.forEach(element => {
            let x = Math.abs(element - target); // calc x
            arr.shift(); // removes first element from arr (current element)
            if (arr.includes(x) && (arr.indexOf(x) != arr.indexOf(element))) {
                newArr.push(element);
                newArr.push(x);
                return;
            }
        });

    return newArr;
}
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