Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to optimize the following Javascript code mention

Below is the code I would like to optimise.
So, Question is that array in mention all value we need to check two value of sum is 8.
If, yes, then we need to find this value of index.

const arr = [1, 2, 3, 4, 5];
const sum = 8;

console.log(arr);
for (let i = 1; i <= arr.length; i++) {
  for (let j = 1; j <= arr.length; j++) {
    let cal = j + i;
    if (cal === sum && j !== i) {
      console.log(arr.indexOf(i));
    }
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try this way

 const arr = [2, 3, 1, 4, 5];
    const sum = 8;
    const indices = {};

    for (let i = 0; i < arr.length; i++) {
      const complement = sum - arr[i];

      if (complement in indices) {
        console.log(`Indices ${indices[complement]} and ${i} add up to ${sum}`);
        break;
      }
      indices[arr[i]] = i;
    }

  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading