[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/copy-sort-array [Back]  [Original]

Copy and sort array
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Copy and sort array

    importance: 5

    We have an array of strings arr. Wed like to have a sorted copy of it, but keep arr unmodified.

    Create a function copySorted(arr) that returns such a copy.

    let arr = ["HTML", "JavaScript", "CSS"];
    
    let sorted = copySorted(arr);
    
    alert( sorted ); // CSS, HTML, JavaScript
    alert( arr ); // HTML, JavaScript, CSS (no changes)
    solution

    We can use slice() to make a copy and run the sort on it:

    function copySorted(arr) {
      return arr.slice().sort();
    }
    
    let arr = ["HTML", "JavaScript", "CSS"];
    
    let sorted = copySorted(arr);
    
    alert( sorted );
    alert( arr );

    Web Proxy Viewer  |  New URL  |  Original Page