I've been trying to create a generic partition function that returns an array of arrays. the function should be made under the following guidelines:
Arguments:
- An array
- A function
Objectives:
Call <function> for each element in <array> passing it the arguments:
element, key, <array>
Return an array that is made up of 2 sub arrays:
0. An array that contains all the values for which <function> returned something truthy
1. An array that contains all the values for which <function> returned something falsy
Here is what I have so far. I get the return of two. I feel like maybe I just have to do the filter function on two separate occasions, but I'm not sure how to put it together. Thoughts and suggestions are highly appreciated.
_.partition = function (collection, test){
var allValues = [];
var matches = [];
var misMatches = [];
_.filter(collection.value, function(value, key, collection){
if (test(value[key], key, collection) === "string"){
matches.push(value[key]);
}else{
misMatches.push(value[key]);
}
});
return allValues.push(matches, misMatches);
}
You're correct about calling the
filter
method on separate occasions. Onefilter
call would obtain the truthy values; the other would obtain the falsy values:You are close, but there are a couple issues I see:
allValues.push
which is notallValues
itself, but rather the new length of the array._.filter
to iterate over array elements and sort them into two arrays. This is strange, since it's not the intended use of_.filter
.If you want a quick and readable solution using
_.filter
, this will work:A more efficient solution which makes only one pass over the collection is below (this is almost what you already have):
Usage examples (and Plunker):
Here is a version which uses
reduce
:Here's an alternative version which uses
Array#filter
to find the matches, and builds an array of non-matches as it goes along: