I'm trying to solve Length of missing array on CodeWars. This is my code.
function getLengthOfMissingArray(arr) {
let result = 0;
if (arr === null || arr.length === 0) return 0;
arr = arr.sort((a, b) => b.length - a.length);
console.log(arr)
for (let i = 0; i < arr.length; i++) {
if (arr[i].length === 0 || arr[i] === null) return 0;
else if (arr[i].length - arr[i + 1].length !== 1) {
console.log(arr[i].length);
console.log(arr[i + 1].length);
result = arr[i].length - 1;
}
}
return result;
}
console.log(getLengthOfMissingArray([
[5, 2, 9],
[4, 5, 1, 1],
[1],
[5, 6, 7, 8, 9]
]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The problem is that I keep getting the TypeError: Cannot read property 'length' of undefined. The console.log(arr[i + 1].length) worked and showing arr[i + 1].length is 1. I'm really confused with this. Can someone help me with this? Thank you!
TypeError: Cannot read property 'length' of undefined
at getLengthOfMissingArray (/home/chrx/Documents/codeWars/Length of missing array.js:8:45)
at Object.<anonymous> (/home/chrx/Documents/codeWars/Length of missing array.js:19:17)
at Module._compile (internal/modules/cjs/loader.js:734:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
at Module.load (internal/modules/cjs/loader.js:626:32)
at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
at Function.Module._load (internal/modules/cjs/loader.js:558:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:797:12)
at executeUserCode (internal/bootstrap/node.js:526:15)
at startMainThreadExecution (internal/bootstrap/node.js:439:3)
iisarr.length - 1?[1,2,3]. The last index in the array is2. Wheni = 2,i + 1is3.arr[3]isundefined.