I’ve tried out various swap algorithms that I see on line but for some reason none of them worked. If fact I copied the scripts I see online and used them in my test code block but they don’t seem to work. All the algorithms do is use a temp variable to temporarily hold a variable but it doesn’t work in any browser. Please my check out test code here.
That’s because you were putting the original value back into the element instance.
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j] = temp;
should be
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
Just out of curiousity, though. Why aren’t you just using the basic sort available in javascript?
Yeah I that was a typo, thangs for catching it
Hi, this is just to make sure something isn’t off on my machine. Lately I’ve been getting errors on my machine or some code don’t work on my machine but they work in jsFiddler.
I’m seeing an issue now. Please check out my code here, for some reason it is not working on my machine.
logging out your last code the result is
["2", "5", "8", "10", "13", "25"]
interestingly (to me anyway) this achieves the same
const json =
'{"10":"name", "2":"Age", "25":"Dep", "8":"Role", "13":"Manager", "5":"Proj"}';
function sortJSON(json) {
return Object.getOwnPropertyNames(JSON.parse(json))
}
console.log(sortJSON(json));
/* ["2", "5", "8", "10", "13", "25"] */
Some discussions on the topic here
You can swap this is one line with array destructuring:
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
Perhaps I’m missing some subtle techicality here, but isn’t this just an issue of strings sorting differently from integers?
I.e.
if (“5” < “10”) …
is very different from
if (5 < 10)
Hi thanks, for your reply. The goal is to find out why the script works in jsFiddle but not on my machine. At first I thought the issue was due to a typo where I was using incorrect array indices on the array elements in the swap but even after checking to make sure they are correct, the code still doesn’t run correctly. It appears to run fine on jsFiddle but not on my machine.
How are you running the script locally? How does it not work? Do you get an error or is the output incorrect?