0

I have a problem when trying to sort an array alphabetically into another array.

This is what the original array looks like:

var palavras = new Array(5);

palavras[0] = "Português";
palavras[1] = "Inglês";
palavras[2] = "Programação C";
palavras[3] = "Programação JS";
palavras[4] = "Educação Física";

I need to sort this array alphabetically into another array but I can't seem to get it to work.

This is the expected output of the other array:

arraySorted[0] = "Educação Física";
arraySorted[1] = "Inglês";
arraySorted[2] = "Português";
arraySorted[3] = "Programação C";
arraySorted[4] = "Programação JS";

I'm new to StackOverflow so I don't know how to use the tools to make it more understandable but I hope someone can help. Thanks!

3
  • use arrayName.sort() function. Commented Jun 17, 2022 at 11:58
  • What have you tried and what didn't work? You can sort an array, but if you don't want the original array sorted then you would need to copy the elements into a new array. Commented Jun 17, 2022 at 11:59
  • 1
    Create a shallow copy of the array const arraySorted = Array.from(palavras), then sort the copy arraySorted.sort((a, b) => a.localeCompare(b)) Commented Jun 17, 2022 at 12:01

1 Answer 1

1

If I understand correctly, You want to keep original array unsorted. So you have to create new array from original one:

arraySorted = palavras.slice()

and then you can sort:

arraySorted.sort()

Array.slice() returns new array, without any param it returns array with the same values and length. Array.sort() changes array original array so without slice you would have both arrays changed

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.