array doesn't want to go away

i want array values that are numbers to be deleted but it doesn't go away and it still shows as ""
No description
16 Replies
13eck
13eck5mo ago
It's because you're using the .map() function, which takes in an array of X items and returns an array of the same number of items. Also, you're creating a new array in each loop for no reason—just return el instead. What you should be using is the .filter() function, which takes in an array of X items and returns an array of that many or less.
const newMix = mix.filter( x => {
if (typeof(x) == "string") return true;
else return false;
});
const newMix = mix.filter( x => {
if (typeof(x) == "string") return true;
else return false;
});
Which can be made even more succient by:
const newMix = mix.filter( x => (typeof(x) == "string") ? true: false);
const newMix = mix.filter( x => (typeof(x) == "string") ? true: false);
Lastly, please use code blocks (putting code between ``` ) so we can copy/paste your code. Going off of a screenshot isn't very helpful.
محمد
محمدOP5mo ago
thanks but i have to use map because it's a homework and i have to do it like this
13eck
13eck5mo ago
.map() won't change the array length, though. It'll always return an array of 11 items (as your initial array has that many items)
محمد
محمدOP5mo ago
so there's no way right
13eck
13eck5mo ago
Not with .map(), no
محمد
محمدOP5mo ago
ok what about .reduce()
13eck
13eck5mo ago
.reduce()? Yes Both .map() and .filter() can be done using .reduce()
محمد
محمدOP5mo ago
that's great
13eck
13eck5mo ago
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce The reduce() function's first parameter is a function that has two parameter: the accumulator (which is the current value passed in from all prior loops) and the value (which is the current value at the index being looped over). You then pass an empty array as the initialValue so you have a new, empty, array to work with. On each loop, you want to check if the value is a string, if it is you add it to the accumulator. If not, you do nothing. Be sure to return the accumulator in the callback function so it can be used in the next loop.
محمد
محمدOP5mo ago
thank you very much really appreciate it
13eck
13eck5mo ago
Sure thing! Hope it helps
dys 🐙
dys 🐙5mo ago
const newMix = mix.filter((x) => (typeof(x) == "string") ? true : false)
I think you mean: const newMix = mix.filter((x) => typeof(x) === 'string') 😸
13eck
13eck5mo ago
That works, too, yeah. I like the ternary operator, what can I say? 😉
dys 🐙
dys 🐙5mo ago
In general, statement ? true : false is an antipattern since your ternary does nothing but complicate reading the logic.
محمد
محمدOP5mo ago
you guys are smart you need to 1v1 each other
13eck
13eck5mo ago
Nah. We’ll tag-team a codebase instead :p
Want results from more Discord servers?
Add your server