Tell us what’s happening:
This code returns the array with the elem on it. What is the trick so I can return the opposite of this, the array without the elem.
Your code so far
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i = 0 ; i<arr.length; i++){
for (let j = 0 ; j < arr[i].length; j++){
if (elem == arr[i][j]){
newArr.push(arr[i]);
}
}
}
// change code above this line
return newArr;
}
// change code here to test different cases:
console.log(filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i = 0 ; i<arr.length; i++){
if (arr[i].indexOf(elem) === -1){
newArr.push(arr[i]);
}
}
// change code above this line
return newArr;
}
If you want to do it using only “for loops” try the below code
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i = 0 ; i<arr.length; i++){
let flag = 1;
for (let j = 0 ; j<arr[i].length; j++){
if (arr[i][j] === elem) {
flag = 0;
break;
}
}
if(flag) {
newArr.push(arr[i]);
}
}
// change code above this line
return newArr;
}
I also have a question regarding this code. The code FCC suggests as an answer is so different from mine that I did not want to just copy it but rather wanted to save my code. I will be glad to hear any suggestions on how this could be fixed:
function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for (let i=0; i<arr.length; i++) {
for ( let j=0; j<arr[i].length; j++)
{
if (arr[i].indexOf(elem)!=-1);{
newArr = arr.splice(arr[i],1);
}
break;
}
Hi @Karajna
I don’t understand why you are looping inside the elements of arr[i]. You never even use your j variable.
Then you have a bad semicolon in this line, which you should remove: if (arr[i].indexOf(elem)!=-1);
Finally, you are using splice on an empty array newArr. I think it would be more logical to:
Check if elem is NOT part of arr[i];
If true, then push the array arr[i] into newArr.
Finally, I don’t like that, in the solution provided, FCC changed a line above the comment let newArr = [...arr];. The comment clearly states to input your code below the 3rd line. What kind of rebelious solution is that?