## DEV Community is a community of 620,183 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# Discussion on: Daily Challenge #215 - Difference of 2

mushtaqasif

JS Solution

``````function pairDifference(data) {
var pairs = [];
var added = [];

data.sort(function(x, y) {
return x - y;
});

for (let i = 0; i < data.length; i++) {
var x = data[i];

for (let j = 0; j < data.length; j++) {
var y = data[j];

if (added.indexOf(x) < 0 && added.indexOf(y) < 0
&& Math.abs(x - y) == 2
) {
pairs.push([x, y]);
added.push(x);
added.push(y);
}
}
}

return pairs;
}

var testData = [
[1, 2, 3, 4],
[4, 1, 2, 3],
[1, 23, 3, 4, 7],
[4, 3, 1, 5, 6],
[1,3,4,6]
];

for (let k = 0; k < testData.length; k++) {
var data = testData[k];

console.log(JSON.stringify(data) + ' --> '
+ JSON.stringify(pairDifference(data)))
}
``````

output:

``````[1,2,3,4] --> [[1,3],[2,4]]
[4,1,2,3] --> [[1,3],[2,4]]
[1,23,3,4,7] --> [[1,3]]
[4,3,1,5,6] --> [[1,3],[4,6]]
[1,3,4,6] --> [[1,3],[4,6]]
``````