0

Im new to software development and have been taking a class, im having an issue with finding out how to remove items in an array based on a 2nd argument character

Write a function "removeWordsWithChar" that takes 2 arguments:

  1. an array of strings
  2. a string of length 1 (ie: a single character) It should return a new array that has all of the items in the first argument except those that contain a character in the second argument (case-insensitive).

Examples:

----removeWordsWithChar(['aaa', 'bbb', 'ccc'], 'b') --> ['aaa', 'ccc']

----removeWordsWithChar(['pizza', 'beer', 'cheese'], 'E') --> ['pizza']

function removeWordsWithChar(arrString, stringLength) {
  const arr2 = [];
 for (let i = 0; i < arrString.length; i++) {
   const thisWord = arrString[i];
    if (thisWord.indexOf(stringLength) === -1) {
     arr2.push(thisWord);
    }
  }
return arr2;
}
  • [Array.prototype.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) `arr2.filter(x=>!x.toLowerCase().includes(strLength.toLowerCase()))` – user120242 Jun 23 '20 at 22:06
  • it should be case insensitive, so use `if (thisWord.toLowerCase().indexOf(stringLength.toLowerCase()) === -1)` – CascadiaJS Jun 23 '20 at 22:09
  • that worked! i cant believe i missed the lowercase. Thank you! – adeel-justice Jun 23 '20 at 22:13
  • you can also use localeCompare https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare – user120242 Jun 23 '20 at 22:15
  • Does this answer your question? [How to do case insensitive string comparison?](https://stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison) – user120242 Jun 23 '20 at 22:15

1 Answers1

1

As they said in comments you can use filter like this:

function removeWordsWithChar(elems, string){
  return elems.filter(elem => !elem.toLowerCase().includes(string.toLowerCase()));
}
mgm793
  • 1,968
  • 15
  • 23