Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
¿Hay alguna manera de hacer que este código Javascript sea más eficiente?

Es un ejercicio simple que estoy haciendo por mera práctica y ocio, lo he hecho de varias maneras pero me preguntaba si hay una forma aún más práctica o para reducir las líneas de código haciendo uso de los muchos métodos de JavaScript.

El ejercicio consiste en recibir una matriz (arr) y un número (objetivo) y devolver otra matriz con un par de números que se encuentran en 'arr' cuya suma es igual a 'objetivo'.

 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 answers
Answer question

0

Si está de acuerdo con una función que solo devuelve un par de números (la primera coincidencia, por así decirlo) cuya suma es igual al valor de los objetivos, esto podría ser suficiente:

 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 Report

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 Report

0

Cambié for loop con forEach (más eficiente) y no hay necesidad de la matriz copyArray, así que la eliminé. También cambié pop () con shift (), creo que desea cambiar la matriz y no abrirla (si entiendo la tarea correctamente).

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!