I’m filtering a given Array using its native .filter() method:
var a = [1,2,3,4,5];
var b = a.filter(function(v) {
return v > 2;
});
That creates the new Array ([3,4,5]). Now, I also want to have the filtered values in another array. What is my best option here? Should I
- push the removed values into a new array within that same filter method ?
- write an invert function and apply it after filtering ?
To go with the first option, it might end up this:
var b = a.filter(function(v) {
return v > 2 || !c.push(v);
});
My problem with that solution is, that it kinda mixes two different things and maybe very confusing for anybody who reads the code in the future. As an alternative, I could call something like
c = invert(a,b);
function invert(source, compare) {
return source.filter(filterPositives);
function filterPositives(v) {
return compare.indexOf(v) === -1;
};
}
Is that effective? Or can I do better ?
Any other (more elegant) ideas how to solve this problem ?
I don’t think going through the source array twice is an elegant solution. But then again, adding side-effects to your own
filteris not great either.I’d solve the problem by writing a
filterSplitfunction, something like this pseudocode:… or, if you’d prefer arrays in your return …