I'm trying to make a function that takes an array as input and a target, and then iterates the array to check if the current index is equal to the target. If so, it will splice the current index from the array.
Everything works fine so far, however when i implement an if statement to check if the index is at the end of the array and then check if the result array is equal to the input array. I really don't know why this is taking me so long it's kind of embarrassing... Here's my code:
let array = ['fox', 'tiger', 'elephant', 'jaguar', 'wolf', 'deer', 'hog', 'dhole', 'leopard', 'eagle', 'bear'];
const splice = (arr, target) => {
//creates empty result array
let result = [];
//iterate through the input array and push each item to the result array
for(let i = 0; i < arr.length; i++) {
result.push(arr[i]);
}
let j = 0;
//iterate through result array
while(j < result.length) {
if (result[j] === target) {
result.splice(j, 1);
}
//i have tried this multiple times with the if statement in and out of the loop
if (j === result.length && result === arr) {
//throw new Error(`${target} was not found in the array`);
console.log({result, arr, j});
return 'equal';
} else if (j === result.length && result !== arr ) {
console.log({result, arr, j});
return 'different';
}
j++;
}
};
//should return 'equal' but returns 'different'
console.log(splice(array, 'turtle'));
//should return 'different' but returns undefined
console.log(splice(array, 'bear'));