Ask coding questions

← Back to all posts
Modify the function to return a copy of the given array sorted in ascending order (1, 2, 3, etc).

function copyAndSortNumbers(numbers) {

}

/ Do not modify code below this line /

const original = [1, 7, 3, 5];
const sortedCopy = copyAndSortNumbers(original);

console.log(original, '<-- should be [1, 7, 3, 5]');
console.log(sortedCopy, '<-- should be [1, 3, 5, 7]');

Commentshotnewtop
ClintDudley1101 (0)

function copyAndSortNumbers(numbers) {
return [].concat(numbers).sort(this.numbers)
}

/ Do not modify code below this line /

const original = [1, 7, 3, 5];
const sortedCopy = copyAndSortNumbers(original);

console.log(original, '<-- should be [1, 7, 3, 5]');
console.log(sortedCopy, '<-- should be [1, 3, 5, 7]');

Blacksheep3y (0)

SOLVED:
function copyAndSortNumbers(numbers) {
var oldArray = numbers;
var newArray = [].concat(oldArray);
return newArray.sort();
}

/ Do not modify code below this line /

const original = [1, 7, 3, 5];
const sortedCopy = copyAndSortNumbers(original);

console.log(original, '<-- should be [1, 7, 3, 5]');
console.log(sortedCopy, '<-- should be [1, 3, 5, 7]');

mwilki7 (1079)

Do they want you to write your own sort function or call a sorting function?

Do they want you to do this:

``````function copyAndSortNumbers(numbers) {
var newarr = [];
for (...)
{
sorty code here
}
return newarr;
}``````

or do they want this?

``````function copyAndSortNumbers(numbers) {
var newarr = numbers;
newarr.sort()
}``````

If it's the 2nd part try:
https://www.w3schools.com/jsref/jsref_sort.asp