Reputation: 13
I have an array, each value of which means a side of the world:
let array = ["NORTH", "SOUTH", "WEST", "EAST"];
If NORTH/SOUTH or EAST/WEST stand together, then these values are removed (SOUTH/NORTH and WEST/EAST are removed too). In this case, the function has to return empty array, instead it returns undefined. Can anyone explain why this is happening. Sorry for the mistakes, I tried not to make them
let array = ["NORTH", "SOUTH", "WEST", "EAST"];
let obj = {
"NORTH": 1,
"SOUTH": -1,
"WEST": 2,
"EAST": -2
}
function dirReduc(arr) {
for (let i = 0; i < arr.length; i++) {
if (i == arr.length - 1 || !arr.length) {
return arr;
} else if (obj[arr[i]] + obj[arr[i + 1]] == 0) {
arr.splice(i, 2);
return dirReduc(arr);
}
}
}
console.log(dirReduc(array));
Upvotes: 0
Views: 100
Reputation: 2832
Your array was getting down to length 0, and the for loop wasn't even running because of that.
for (let i = 0; i < arr.length; i++) {
Upvotes: 0
Reputation: 350137
When your recursive function splices away all content, like in the example, the deepest nested call of the function will not iterate the loop (as the array is empty), and return undefined
. This value will be returned also from the point where the recursive call was made, and so also the main call will return undefined
.
I would suggest not using recursion, but iterate backwards. That way the splice
call does not influence the array iteration negatively, and you'll only do one sweep over the array:
function dirReduc(arr) {
for (let i = arr.length-2; i >= 0; i--) {
if (obj[arr[i]] + obj[arr[i + 1]] == 0) arr.splice(i, 2);
}
return arr;
}
Upvotes: 1
Reputation: 187
You can modify is as following:
let array = ["NORTH", "SOUTH", "WEST", "EAST"];
let obj = {
"NORTH": 1,
"SOUTH": -1,
"WEST": 2,
"EAST": -2
}
function dirReduc(arr) {
for (let i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
return arr;
} else if (obj[arr[i]] + obj[arr[i + 1]] == 0) {
arr.splice(i, 2);
if (arr.length == 0)
return [];
return dirReduc(arr);
}
}
}
console.log(dirReduc(array));
Hope this helps.
Upvotes: 0