简体   繁体   中英

how do I repeatedly reorder array's elements without mutating the array itself?

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.

more explanation:

  1. taking an original arr
  2. swapping the first pair of numbers
  3. returning [2,1,3,4]

repeating

  1. taking an original arr
  2. swapping the second pair of numbers
  3. returning [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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM