Home > Mobile >  Is there a way to make this Javascript code more efficient?
Is there a way to make this Javascript code more efficient?

Time:11-22

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

CodePudding user response:

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

CodePudding user response:

use Array.filter to find the target sum for all values in an given array. See comments in the snippet.

const testArr = [...Array(20)].map( (_, i) => i);
const target = Math.floor(Math.random() * 30);

document.querySelector(`pre`).textContent = `testArray: ${
  JSON.stringify(testArr)}\ntarget: ${target}\nResult: ${
  JSON.stringify(targetSum(testArr, target))}`;

function targetSum(arr, target) {
  // clone the array
  const clone = arr.slice();
  let result = [];

  while (clone.length) {
    // retrieve the current value (shifting it from the clone)
    const current = clone.shift();
    // filter arr: all values where value   sum  = target
    const isTarget = arr.filter(v => current   v === target);
    // add to result. 
    // Sorting is to prevent duplicates later
    if (isTarget.length) {
      result = [...result, ...isTarget.map(v => [current, v].sort())];
    }
  }
  
  // weed out duplicates (e.g. 0   3, 3   0)
  const unique = new Set();
  result.forEach( r => unique.add(`${r[0]},${r[1]}`) );
  
  // return array of array(2)
  return [...unique].map(v => v.split(`,`).map(Number));
}
<pre></pre>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related