user15030493
user15030493

Reputation:

Get pair of elements from array whose value is equal to specific sum using javascript

Given an array as [2, 7, 5, 3, 9] I was trying to find the pair of values from the array whose sum would be equal to 12 and below is the code that I wrote

let arr1 = [2, 7, 5, 3, 9]
let addSum = 12;

for (let i = 0; i < arr1.length; i++) {
  let diff = addSum - arr1[i];
  if (arr1.includes(diff)) {
    console.log('Arr pair has value' + diff + ': ' + arr1[i]);
  }
}

but the issue i'm facing is the value are duplicated in the console as given below -

Arr pair has value5: 7
Arr pair has value7: 5
Arr pair has value9: 3
Arr pair has value3: 9

if i already have (5,7) it should not be repeated as (7,5) how can I do that?

Upvotes: 1

Views: 593

Answers (3)

Jack Bashford
Jack Bashford

Reputation: 44087

If you just want to strip duplicates from your list of results, store each diff in an array and check if the diff or the diff's difference already exist as a pair:

let arr1 = [2, 7, 5, 3, 9]
let addSum = 12;
let diffs = [];

for (let i = 0; i < arr1.length; i++) {
  let diff = addSum - arr1[i];
  if (arr1.includes(diff)) {
    diffs.push(diff);
    if (!diffs.includes(addSum - diff)) {
      console.log('Arr pair has value ' + diff + ':' + arr1[i]);
    } else {
      diffs.push(arr1[i]);
    }
  }
}

Upvotes: 0

Barmar
Barmar

Reputation: 780724

Only print the cases where diff is less than arr[i].

let arr1 = [2, 7, 5, 3, 9]
let addSum = 12;

for (let i = 0; i < arr1.length; i++) {
  let diff = addSum - arr1[i];
  if (diff < arr1[i] && arr1.includes(diff)) {
    console.log('Arr pair has value ' + diff + ': ' + arr1[i]);
  }
}

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370669

The simplest solution would be to remove the other item index from the array when found:

let arr = [2, 7, 5, 3, 9]
let addSum = 12;

for (let i = 0; i < arr.length; i++){
    let diff = addSum - arr[i];
    const index = arr.indexOf(diff);
    if (index !== -1) {
        console.log('Arr pair has value' + arr[index] + ': '+arr[i]);
        arr.splice(index, 1);
        i--; // to avoid skipping the next one from the array indicies shifting down
    }
}

Another solution with better time complexity (O(n) instead of O(n ^ 2)) would be to put the items into a Set instead, assuming duplicates aren't an issue:

const set = new Set([2, 7, 5, 3, 9]);
let addSum = 12;
for (const item of set) {
  const diff = addSum - item;
  if (set.has(diff)) {
    console.log('Arr pair has value' + item + ': '+diff);
    set.delete(diff);
  }
}

If duplicates are a possibility you need to account for, use a Map (or object) instead, where the values are the number of times the key (the number) has been found in the original array. When a key that matches a diff is found, log only if the value is greater than 0, and decrement that value.

Upvotes: 2

Related Questions