1

I am solving a practice problem in Practice-it and there is a question that is saying to creating an empty array inside a function and pass the array of strings as an argument into the function and to remove a specific word from it.

Here is the question: Write a function named removeAll that accepts an array of Strings and a single String as parameters, and returns a new array. The returned array should be equivalent to the parameter array but with all occurrences of the String parameter removed, ignoring case. The array parameter should remain unchanged as a result of the function call. For example, if an array named words contains ["foo", "bar", "baz", "Foo", "FOO"], the call of removeAll(words, "foo") should return ["bar", "baz"].

My code: I am getting undefined

function removeAll(words, remove){
  let arr = [];
  remove = '';
  arr = arr.filter(words => words !== remove);
}

removeAll(["foo", "bar", "baz"], "foo");

Any help would be appreciated. Thank you!

4
  • why are you setting remove to '' ? Commented Dec 1, 2017 at 2:19
  • 3
    You should filter words, not arr Commented Dec 1, 2017 at 2:20
  • function removeAll(words, remove){ words = words.filter(word => word !== remove); } Commented Dec 1, 2017 at 2:22
  • 1
    You do not return anything.... and your code does not handle cases Commented Dec 1, 2017 at 2:26

3 Answers 3

2

Your close, but you have 2 mistakes. Do not set remove to ''. And filter words not arr

function removeAll(words, remove){
  return words.filter(word => word.toLowerCase() !== remove.toLowerCase());
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are using the variables internally in the wrong way.

// toLowerCase to compare lowercase strings
function removeAll(words, remove){
  return words.filter(word => 
    word.toLowerCase() !== remove.toLowerCase()
  );
}

console.log(removeAll(["foo", "bar", "baz", "FOO"], "foo"));


// Using Arrow functions
removeAllES6 = (words, remove) => 
   words.filter(word => word.toLowerCase() !== remove.toLowerCase())

console.log(removeAllES6(["foo", "bar", "baz", "FOO"], "foo"));

Comments

1

Additionally to what is already mentioned, since you need a case insensitive comparision, use toLowerCase() or toUpperCase()

function removeAll(words, remove){
  return words.filter(words => words.toUpperCase() !== remove.toUpperCase());
}

arr = removeAll(["foo", "bar", "baz"], "foO");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.