how can I convert an array like:
[2, 5, 4, 0]
into an array of pairs but not getting every pair. For example from the above array given, I'd like the following array:
[[2, 5],[5, 4], [4, 0], [0, 2]
.
Furthermore, is it possible to have another function that gives back an array like: [[2,5,4],[5,4,0],[4,0,2],[0,2,5]]
?
And also another one that gives back: [[2,5,4,0],[5,4,0,2],[4,0,2,5],[0,2,5,4]]
?
Edit: I have tried the following which gives back every possible pair in the array, but it's not what I'm looking for:
let result = pieces[0].reduce( (acc, v, i) =>
acc.concat(pieces[0].slice(i 1).map( w => [v, w] )),
[]);
This will show: [ [ 2, 5 ], [ 2, 4 ], [ 2, 0 ], [ 5, 4 ], [ 5, 0 ], [ 4, 0 ] ]
Edit2: my problem here is that everything I have tried gives me every permutation of the two dimensional, three dimensional and four dimensional arrays, but I only want the examples above. Let's say, the permutation of consecutive values.
CodePudding user response:
I believe this is what you are looking for:
let arr = [2, 5, 4, 0]
function getPermutation(chunk){
let result = arr.reduce((acc,e,i) => {
if(i chunk <= arr.length)
acc.push(arr.slice(i,i chunk))
else
acc.push(arr.slice(i,i chunk).concat(arr.slice(0,(i chunk) % arr.length)))
return acc;
},[])
return result
}
console.log(getPermutation(2))
console.log(getPermutation(3))
console.log(getPermutation(4))
CodePudding user response:
Here is one way to do it:
const input = [2, 5, 4, 0];
const output = [];
for(let i=0; i<input.length - 1; i ) {
output.push([input[i], input[i 1]]);
}
output.push([input[input.length-1], input[0]]);
console.log(output);