I need to sort the following array by the 2nd element of the contained tuple. The process runs through, until the last element has passed. After that I get the exception
ERROR TypeError: Cannot read property '1' of undefined
Here is my used Code:
public list:Array<[string, number]> = new Array<[string, number]>();
//{["A", 0],["B", 8], ...}
...
var sorted = false
while (!sorted){
sorted = true;
this.list.forEach(function (element, index, array){
alert(element);
if (element[1] > array[index+1][1] ) {
array[index][1] = array[index+1][1];
array[index+1] = element;
sorted = false;
}
});
}
I can't get, why this isn't working
This line:
array[index+1][1];
causes
ERROR TypeError: Cannot read property '1' of undefined
Thats because when the iteration reaches the last index, e.g 5
, it tries to take 6
from the array, which obviously does not exist. So you need to skip the last index while iterating, e.g.:
if(array.length - 1 === index)
return;
How i would do that:
var sorted = false;
while(!sorted){
sorted = true;
for(let index = 1; index < array.length; index++) {
if(array[index][1] < array[index - 1][1]) {
([array[index], array[index - 1]] = [array[index - 1], array[index]]);
sorted = false;
}
}
or much simpler:
array.sort((a, b) => a[1] - b[1])