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

258
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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