Home > Blockchain >  How Node JS Map Of Values Adds Up to K
How Node JS Map Of Values Adds Up to K

Time:11-30

Given a list of numbers const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];and a number k say const k = 17;, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k = 17, we should return True, since 10 7 =17.

Wrote below code using key,values in Map,but seems not able to get the solution,can anyone suggest what code change is needed below ,want to solve especially using Maps

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
const k = 17;
let addInput = new Map(arr.flatMap((x) => Object.entries(x)));

addInput.forEach((v) => {
  for (var i = 0; i < addInput.size; i  ) {
    if (v != addInput[i]) {
      if (addInput[i]   v == k) {
        console.log(`${v}   ${addInput[i]} = ${k} (true)`);
      }
    }
  }
});

CodePudding user response:

The approach is unclear with your code: You should use Set to remove duplicate not Map and you should use map operator to extract the values from the object, you also can't access map operator with number index like array.

const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];
const k = 17;
// using set to remove duplicate
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));

// using array to iterate easily, convert by destruturing
let valueArray = [...valueSet];

valueArray.forEach((v1, i1) => {
  for (let i2 = i1   1 ; i2 < valueArray.length; i2  ) {
      if ((v1   valueArray[i2]) === k) {
        console.log(`${v1}   ${valueArray[i2]} = ${k} (true)`);
      }
  }
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related