← 返回首页
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
    Search
    Light themeDark theme
    عربيDanskEnglishEspañolفارسیFrançaisIndonesiaItaliano日本語한국어РусскийTürkçeУкраїнськаOʻzbek简体中文
    back to the lesson

    Copy and sort array

    importance: 5

    We have an array of strings arr. We’d 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 );