I’m doing for-loop practice and can only use for loops to iterate over the arrays and strings in the problems I’m working.
QUESTION:Return and array of 2 arrays
// (1 – an array of names that contain "a" in name, 2 – an array of names that don’t have ‘a’ in name)
I know how to push the names containing the letter ‘a’ to an array but the names that don’t contain the letter a, are being pushed into the array as many times as it’s being iterated over, how can I have the array of names that doesn’t contain the letter ‘a’ only contain the name once and not as many times as its iterated over I know the issue lies somewhere is me having the for loop nested I think but I just cant see it, any tips or advice are welcome !
const arr1 = ['susan', 'meghan', 'timmy', 'tommy', 'thomas'];
function itsSomething(array) {
let bothArrays = [];
let withA = [];
let withoutA = [];
for (let i = 0; i < array.length; i++) {
let name = array[i];
for (let x = 0; x < name.length; x++) {
if (name[x] == 'a') {
withA.push(name)
} else {
withoutA.push(name)
}
}
}
bothArrays.push(withA, withoutA);
return bothArrays
}
console.log(itsSomething(arr1))
2
Answers
There are two problems with your code:
a
you should break out of the loop. Otherwise if the word has multiplea
you’ll push it towithA
multiple times.withoutA
whenever you find a non-a
character, but there could still be ana
later in the string. You have to wait until the end of the word to know if it had ana
in it. Use a flag variable to hold this information.There’s no need for the
bothArrays
variable. You can simply create that array when you’re returning the two arrays.here i bring you two solutions, first the easiest solution is using the method includes, like this:
}
if you are practicing loops the best way is how Barmar mentioned, using a flag variable to avoid pushing unnecessary names, like this
}
in terms of performance i will strongly suggest you to use the first solution it has a
a time complexity of O(n), while the second solution has a time complexity of O(n * m) for all the nested loops. hope this helps!