Search code examples
google-apps-scriptgoogle-slides-apigoogle-slides

I need to reverse the selected slide order using Google Apps script


I need to reverse the order of selected slides (if there is selection) otherwise reverse all the slides.

here is the code script editor file

example slides 2 and slide 4 when selected then after the code execution

Before: S1,S2,S3,S4
Expected result: S1,S4,S3,S2

If no slides are selected

Before: S1,S2,S3,S4
Expected result: S4,S3,S2,S1

If slide 1, slide 2 and slide4 are selected

Before: S1,S2,S3,S4
Expected result: S4,S2,S3,S1

I have tried with

selectedArrayIndex = selectedArrayIndex.reverse();
for (var k = selectedArrayIndex.length - 1; k >= 0; k--) {
    allSlides[k].move(selectedArrayIndex[k] + 1);
}

Solution

  • Answer

    As per the documentation says The index should be between zero and the number of slides in the presentation, inclusive.

    Once you move a slide the entire presentation slides change their indexes, for that reason the best way to achieve your goal is change the last slide first and not backwards, because by doing it you can keep the presentation slides indexes ordered.

    Let's say you have this scenario, you want to change S1, S2 and S4:

    S1 -> index 1
    S2 -> index 2
    S3 -> index 3
    S4 -> index 4
    

    What you actually get by moving the first slide to the last position is:

    First step        Second step       Third step
    S2 -> index 1  |  S3 -> index 1  |  S3 -> index 1
    S3 -> index 2  |  S2 -> index 2  |  S4 -> index 2
    S4 -> index 3  |  S4 -> index 3  |  S2 -> index 3
    S1 -> index 4  |  S1 -> index 4  |  S1 -> index 4
    

    What you get by moving the last slide to the first position is:

    First step        Second step       Third step
    S4 -> index 1  |  S4 -> index 1  |  S4 -> index 1
    S1 -> index 2  |  S2 -> index 2  |  S2 -> index 2
    S2 -> index 3  |  S1 -> index 3  |  S3 -> index 3
    S3 -> index 4  |  S3 -> index 4  |  S1 -> index 4
    

    Code

    In order to get your expected behaviour you should use this code in the last loop in your code.

    // selectedArrayIndex = selectedArrayIndex.reverse(); No need to reverse the array
    var len = selectedArrayIndex.length
    for (var k = len - 1; k >= 0; k--) {
        allSlides[selectedArrayIndex[k]].move(selectedArrayIndex[len - 1 - k] + 1);
    }