Message from JavaScript discussions

August 2020

β€” Eggheaddidation is thinking that there is some chance that things like YEW will take over lol

β€” 

On the topic of edge, does anyone here play edge://surf (admittedly it's a completely unrelated question)

β€” Lol

β€” Btw i think i recon who is destined to become a popular tech bloggerπŸ€”

β€” Hi Everyone,

i'm new to JS.

So,I stared solving a code challenge and this is the requirement.

Given an array of different type of elements as below.

[
"cat",
2,
0,
null,
["-1", undefined, {}, 7, ["car", "dog", 5, [2, 19], 2]],
];

I should return an array of only numbers.



I solved the code but when I used .push instead of .contact inside the reduce array method I got an error saying push isn't a function.


Can anyone please explain about the error and why shouldn't I use .push instead of .concat in this case.

Message permanent page

β€” Code :


const arr = [
"cat",
2,
0,
null,
["-1", undefined, {}, 7, ["car", "dog", 5, [2, 19], 2]],
];

const flatten = (array) => {
return array.reduce((result, item) => {
return result.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
};
console.log(flatten(arr).filter((item) => typeof item === "number"));

Message permanent page

β€” Push is stateful, concat is stateless.
Which means push mutates the original array, whereas reduce expects to use the return value for the next iteration.

Message permanent page

β€” So concat is better in this case

β€” Can u explain in more detail ?

β€” So,push changes the the original array value and when in the next iteration as the value already changed ( coz we used push ) it doesn't work ?

Message permanent page

β€” Exactly. let me try it myself . 1 second

β€” Ok. .push would have also worked - but it does not return the array, it returns the new length of the array

Message permanent page