Skip to content

Instantly share code, notes, and snippets.

@AbdQaadir
Last active April 19, 2021 14:26
Show Gist options
  • Save AbdQaadir/f69e677b34f9c69c809f7d02c355f8cc to your computer and use it in GitHub Desktop.
Save AbdQaadir/f69e677b34f9c69c809f7d02c355f8cc to your computer and use it in GitHub Desktop.
const removeInstances = ({arr, val}) => {
const arrLength = arr.length;
if(arrLength === 0) throw new Error("Array cannot be empty");
//Return the orginal length of array if no number is passed in.
if(!val) return arrLength;
const filteredArray = arr.filter((num) => num !== val);
return filteredArray.length;
};
const arr = [5,2,2,5,3];
const val = 5;
console.log(removeInstances({arr, val}));
@meekg33k
Copy link

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

Your solution works for most of the test cases; however it assumes that the input array arr cannot have a null or undefined value because if I run removeInstances({ arr: null, val}), your code will break on line 3. Ideally you want to write robust code that can handle unexpected input and fail gracefully without causing runtime errors.

Also I like that you used JavaScript's in-built filter function. What do you think are the trade-offs with using the filter function?

I've posted my solution here. Do let me know what you think.

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