Reputation: 15
I am trying to sort array items and I wrote this function. It works if I enter only positive numbers, but when I enter negative numbers it doesn't. Can anyone explain to me what is wrong with my code?
function highAndLow(numbers) {
let sort;
let result = '';
let array = numbers.split(' ');
sort = array.sort((a, b) => {
if (a > b) {
return 1;
} else return -1;
});
result = sort[sort.length - 1] + ' ' + sort[0];
console.log(sort);
console.log(result);
}
highAndLow('3 4 6 8 2 3 5 6 1 0'); // sort: 0,1,2,3,3,4,5,6,6,8
highAndLow('99 8 7 6 5 3 8 9 0 0 1 9'); //sort: 0,0,1,3,5,6,7,8,8,9,9,99
highAndLow('-3 -4 1 9 8 -8 1 2 -11'); //sort: -11,-3,-4,-8,1,1,2,8,9
Upvotes: 0
Views: 348
Reputation: 386680
You could omit the mapping and use the delta for sorting. This convert stringed numbers to numbers.
function highAndLow(numbers) {
let array = numbers
.split(' ')
.sort((a, b) => a - b);
console.log(array[array.length - 1] + ' ' + array[0]);
}
highAndLow('3 4 6 8 2 3 5 6 1 0'); // result: 0,1,2,3,3,4,5,6,6,8
highAndLow('99 8 7 6 5 3 8 9 0 0 1 9'); //result: 0,0,1,3,5,6,7,8,8,9,9,99
highAndLow('-3 -4 1 9 8 -8 1 2 -11'); //result: -11,-3,-4,-8,1,1,2,8,9
Upvotes: 1
Reputation: 89374
You can use a - b
in your sort function so that the strings are converted to numbers for sorting.
function highAndLow(numbers) {
let sort;
let result = '';
let array = numbers.split(' ');
sort = array.sort((a, b) => a - b);
result = sort[sort.length - 1] + ' ' + sort[0];
console.log(...sort);
console.log(result);
}
highAndLow('3 4 6 8 2 3 5 6 1 0');
highAndLow('99 8 7 6 5 3 8 9 0 0 1 9');
highAndLow('-3 -4 1 9 8 -8 1 2 -11');
Upvotes: 1
Reputation: 169269
You're sorting the numbers as strings, not as, well, numbers.
Use parseInt
to convert them.
function highAndLow(numbers) {
let sort;
let result = "";
let array = numbers.split(" ").map(n => parseInt(n, 10)); // this map makes them numbers
sort = array.sort((a, b) => {
if (a > b) {
return 1;
} else return -1;
});
result = sort[sort.length - 1] + " " + sort[0];
alert(sort);
alert(result);
}
Upvotes: 2