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; }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; }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)); // nullCambié 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; }