My array is supposed to filter out all of the elements that are not numbers and whats to remain in my array are numbers. Here is a link to my code:https://codepen.io/noblegas/pen/abzyGBp
I’m not seeing any code that filters out undesired values?
Here is what thee output of the function is supposed to look like in the code.
// filter_list([1,2,‘a’,‘b’]) == [1,2]
// filter_list([1,‘a’,‘b’,0,15]) == [1,0,15]
// filter_list([1,2,‘aasf’,‘1’,‘123’,123]) == [1,2,123]
What algorithm have you developed to accomplish the task?
OK. What have you tried to get this to work? I don’t see any code removing values from your array. It just looks like you are printing values that ==="string"
.
Well I didn’t use a built in function that removes that because I used the if(!typeof arr===“string”) condition that is supposed to return any element in the array thats not a string
But you aren’t actually filtering out any values.
I thought it would. Why doesn’t it
You do not have to use a built-in method like filter, but it would be much easier if you did. Either way, all you are doing now is iterating through properties/indices of arr and if the type of the element located at the index of the array is not a string, you are displaying it to the console. This does not filter anything. It just displays elements that are not strings.
You should be returning from the function filter_list
a new list that only contains the numbers from the original list. You are currently only printing the non string values in the array.
so with a filter() method , I don’t need to use a for loop?
No, it will iterate through the entire array.
It worked!
function filterList(arr){
const result=arr.filter(elem=>typeof elem=='number');
console.log(result);
}
filterList([1,2,4,3])
filterList([1,2,‘a’,‘b’])
filterList([1,‘a’,‘b’,0,15]);
What if I pass the following arr?
filterList([1, 2, '1', NaN, 6]);
I get the TypeError arr.filter() is not a function. hmm…
Sorry about that. I did not pass an array. I have edited my last reply.
Okay. my function doesn’t filter out the NaN. NaN stands for not a number.
NaN is type of number. So maybe I should write it in such a way that I make an exception for NaN
I tried this solution but it did nothing.
function filterList(arr){
const result=arr.filter(elem=>typeof elem=='number' && elem!=NaN);
console.log(result);
}
Am I at least on the right track?
You can not directly compare a value to NaN like that. Do some research on comparing values to NaN.