the title explains it all
somehow I’d like to use the method “Combination” that math has, this is the Wikipedia page to be clear: https://en.wikipedia.org/wiki/Combination
I have already found the solution with two loops, I want to do it in one loop
example:
JavaScript
x
13
13
1
const arr = [1, 2, 3, 4]
2
3
function getPairs(arr) {
4
/*
5
desired return:
6
[
7
[1, 2], [1, 3], [1, 4],
8
[2, 3], [2, 4],
9
[3, 4]
10
]
11
*/
12
}
13
Advertisement
Answer
You can use Array.flatMap()
to iterate the array, and Array.map()
to iterate all items after the current (by slicing from index + 1), and return the pair.
JavaScript
1
7
1
const getPairs = arr => arr.flatMap((a, i) => arr.slice(i + 1).map(b => [a, b]))
2
3
const arr = [1, 2, 3, 4]
4
5
const result = getPairs(arr)
6
7
console.log(result)