Reputation: 17
I'm trying to return an array of numbers in descending order (biggest in the front).
My function seems to work but just quits in the middle.
let array = [1, 9, 8, 7, 2, 6, 3, 5];
let sorted = [];
function sortNumbers(array) {
for (var i = 0; i < array.length; i++) {
let max = array.reduce(function(a, b) {
console.log(`a: ${a} b: ${b}`);
return Math.max(a, b);
});
let maxIdx = array.indexOf(max);
let biggest = array.splice(maxIdx, 1);
sorted.push(biggest);
}
console.log('sorted array is: ', sorted.join(''));
//returns 9876
}
sortNumbers(array);
Upvotes: 1
Views: 895
Reputation: 199
use Underscore.Js for doing various manipulations on Arrays and Objects.
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects
go to following the link: https://underscorejs.org/#
_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
Upvotes: 0
Reputation: 92460
The problem you are having is being caused by splicing
inside the loop. You change the array as you're looping through it. The quick fix is to loop through the array backwards so you set the correct length at the beginning of the loop:
for (var i = array.length; i > 0; i--) {
// etc
}
let array = [1, 9, 8, 7, 2, 6, 3, 5];
let sorted = [];
function sortNumbers(array) {
for (var i = array.length; i > 0; i--) {
let max = array.reduce(function(a, b) {
console.log(`a: ${a} b: ${b}`);
return Math.max(a, b);
});
let maxIdx = array.indexOf(max);
let biggest = array.splice(maxIdx, 1);
sorted.push(biggest);
}
console.log('sorted array is: ', sorted.join('')); //returns 9876
}
sortNumbers(array);
Upvotes: 2
Reputation: 57175
As mentioned by others, it's generally risky to splice the array while looping over it. Looping backwards can help avoid issues where elements are removed and the index is thrown off, skipping elements, causing logic errors or throwing out of bounds exceptions.
Having said that, it seems you're attempting selection sort; however, if you're just trying to sort the array in reverse and join, your approach can be simplified to:
const array = [1, 9, 8, 7, 2, 6, 3, 5];
const sorted = array.sort((a, b) => b - a);
console.log(sorted.join(""));
Upvotes: 1
Reputation: 292
Is there a reason you're doing this yourself?
console.log(array.sort(function(a, b) { return a<b ? 1 : a>b ? -1 : 0; } ))
console.log(array.sort().reverse())
Upvotes: 0