I have array const arr = [1,2,3,4]
I want to get 4 different arrays by swapping a number pairs in this array. I. e. the outcome of this array would be:
1st: [2,1,3,4]
2nd: [1,3,2,4]
3rd: [1,2,4,3]
4rd: [4,2,3,1]
(swapping first and last elements)
I know Object.assign
help's to avoid mutations but not sure how to implement it.
[2,1,3,4]
repeating
[1,3,2,4]
etc.
Looks like for any given array, you are going to produce an array of arrays characterized by single swaps. What's important to note is that this array of arrays has the same length (n) as the original array and that the i th array swaps elements i and (i+1)%n. Knowing that, here's a solution using map, Object.assign, and slice:
[ 1, 2, 3, 4 ].map( ( element, index, arr ) =>
Object.assign( arr.slice(), {
[ index ]: arr[ ( index + 1 ) % arr.length ],
[ ( index + 1 ) % arr.length ]: arr[ index ]
} ) );
Note element
is unused.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.