Skip to content

Instantly share code, notes, and snippets.

@daviddamilola
Created April 16, 2021 21:27
Show Gist options
  • Save daviddamilola/0a1055d835ac38118d9e3d9b6f4a8538 to your computer and use it in GitHub Desktop.
Save daviddamilola/0a1055d835ac38118d9e3d9b6f4a8538 to your computer and use it in GitHub Desktop.
returns the length new array after removing provided instance
const removeInstance = (array=[], val=null) => {
if(!Array.isArray(array)) return 0;
if(!val) return array.length;
let currIndex = array.indexOf(val);
while(currIndex !== -1){
array.splice(currIndex, 1)
currIndex = array.indexOf(val);
}
return array.length
}
console.log(removeInstance([1,2,1,2,3,4,5], 1))
console.log(removeInstance(null))
console.log(removeInstance([1], null))
@meekg33k
Copy link

Hello @daviddamilola, thank you for participating in Week 2 of Algorithm Fridays.

This is a more robust solution, definitely an improvement from last week. Kudos to you!

Is there a reason why you used JavaScript's indexOf function? What do you think of looping through the array and comparing each element in the array with val?

I've posted my solution here. Please read through and let me know what you think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment