-3

I am trying to filter an array (like ["hello", "hi", "bye"]) for a specific character (like "h") so that it returns a new array containing only Strings that have that character (["hello", "hi", "bye"] -> ["hello", "hi"]).

Here is my current code. giveSOFT returns [] for some reason.

function giveSOFT(input, char) {
    var length = input.length
    var sublist = []
    var word = ""
    var w = "piss"

    for (let i = 0; i < input.length; i++) {
        word = input[i]
        for (let b = 0; b < word.length; b++) {
            var input = word[b]
            var n = input.includes(w)
            if (n === true) {
                console.log(input)
            }
            return sublist
        }
    }
}

var input = ["piss", "wii", "ww", "iiwi", "iii", "piss"]
var char = "i"

console.log(giveSOFT(input, char));

I don't understand why or how to fix this so any advice would be appreciated.

Here is my exact instructions on what I am trying to do:

Create a function that takes two arguments: a list of words and a letter. The function should create and return a sublist of the list in the argument. The sublist should contain only those words from the original list which contain the letter passed as the second argument. Use .indexOf() to find if the letter passed as an argument is in the word, if it is - push it to a new list, if not - skip

TDStuart
  • 40
  • 4
Jay
  • 1
  • 2
  • `[]` means an empty array. In your case, that's `sublist`, which you initialized as `[]`, but then never modified and simply returned back at the end of the function. – Scott Marcus Feb 05 '21 at 19:01
  • `input.filter(word => word.indexOf(char) != -1)` – Mulan Feb 05 '21 at 19:01
  • 1
    Does this answer your question? [Difference between console.log and return in javascript?](https://stackoverflow.com/questions/21020608/difference-between-console-log-and-return-in-javascript) – PM 77-1 Feb 05 '21 at 19:03

2 Answers2

1

You haven't pushed anything to sublist and your second for loop isn't needed. Also your return is in your for loop not the end of the function.

function giveSOFT(input, char) {
  var sublist = []
  var word

  for (let i = 0; i < input.length; i++) {
    word = input[i]
    if (word.indexOf(char) > -1) sublist.push(word)
  }
  return sublist
}

var input = ["piss", "wii", "ww", "iiwi", "iii", "piss"]
var char = "w"

console.log(giveSOFT(input, char));
imvain2
  • 15,480
  • 1
  • 16
  • 21
0

You didn't push any word to sublist. You can use indexOf function to check that each word contains a specific char or not. It returns the index if the character is found and -1 if not.

function giveSOFT(input, char)
{
  let sublist = []

  for(let i = 0; i < input.length; i++)
    if (input[i].indexOf(char) != -1) sublist.push(input[i]);
  return sublist
}

let input = ["piss","wii","ww","iiwi","iii","piss"]
let char = "i"

console.log(giveSOFT(input,char));
ZaO Lover
  • 433
  • 2
  • 13