I've following two different approaches and confused on which one is recommended and why in terms of readability and memory allocation. As per my understanding both are same in terms of space complexity both(two variables in first approach and accumulator in reduce method) takes space. Which approach is recommended?
Approach 1:
const getFilters = () => {
const filters1 = [];
const filters2 = [];
// assume filters is an array of numbers
filters.forEach(filter => {
if(filter === 1) {
filters1.push(filter);
} else {
filters2.push(filter);
}
})
return {
filter1,
filter2,
}
}
Approach 2:
const getFilters = () => {
// assume filters is an array of numbers
return filters.reduce(
(accumulator, filter) => {
if (filter === 1) {
accumulator.filters1.push(filter);
} else {
accumulator.filters2.push(filter);
}
},
{
filters1: [],
filters2: [],
},
);
}