This question deals with my algorithm and why it isn't working. More specifically, I would like to know how it can be improved to do what I want it to do. That is why it is different from the suggested duplicate question.
I am trying to create a function that sorts an array of objects based on a property value (int) that they all share in common, "indexFound". As you may suspect, I am trying to place elements with a lower indexFound at the beginning of the array.
function organizeTokens(list) {
for (i = 0; i < list.length - 1; i++) {
if (list[i].indexFound < list[i + 1].indexFound) {
// do nothing
} else if (list[i].indexFound > list[i + 1].indexFound) {
var tempVal = list[i];
list[i] = list[i + 1];
list[i + 1] = tempVal;
} else {
// should not happen unless we are comparing the same token
}
}
};
As it stands, this code is not making any difference when I feed it an array of objects. The elements are still not in the order that they should be. Am I approaching this in the right way? Am I missing something obvious?
EDIT: -------------------------------------------------------------------
Example input: organizeTokens([{value: "if", indexFound: 7}, {value: "a", indexFound: 0}])
Expected output: [{value: "a", indexFound: 0}, {value: "if", indexFound: 7}]
Actual output: [{value: "if", indexFound: 7}, {value: "a", indexFound: 0}]