Message from JavaScript discussions

August 2020

— 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"));

— 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

— If you do result.push('whatever'); return result that would work

— But concat is a lot better here, because we can use the return value directly, and we do not need to mutate anything

Message permanent page

— Thanks mate🤝

— Example:

[1,2,3].reduce((result, item) => {
result.push(item)
return result
}, [])