JSFiddle - React, Tailwind, and code Playground
by Farzad YZ
JavaScript
console.clear();
function findPairs1(array, k) {
const pairs = [];
for (let i = 0; i < array.length; i++) {
const v = array[i]
const pairIndex = array.indexOf(k - v)
if (pairIndex !== -1) {
if (k == 2 * v && array.filter(a => a == v).length < 2) {
continue;
}
pairs.push([v, k - v]);
array.splice(i, 1);
array.splice(array.indexOf(k - v), 1)
}
}
return pairs;
}
function findPairs2(array, k) {
const map = {};
const pairs = []
array.forEach((v, i) => {
map[v] = (map[v] || 0) + 1
});
for (const v in map) {
if (k == 2 * v && map[v] < 2) {
continue;
}
if (map[k - v] !== undefined) {
pairs.push([+v, k - v]);
delete map[v];
delete map[k - v];
}
}
return pairs;
}
/*
* [1,4,3,12,124,9,-6,0]
*/
console.log(findPairs1([1, 4, 3, 12, 124, 9, -6, 0], 6))
console.log(findPairs2([1, 4, 3, 12, 124, 9, -6, 0], 6))