The ability to filter data to a subset of itself is an important thing to understand when you are a software engineer, data scientist or otherwise working with data in some form. In this article we will take a look at how we may create our own implementation of the native filter functionality that is available in some form in most common languages. In our case the language of choice will be JavaScript.
In most implementations the filter function will take apredicate to test each item in the collection and if the predicate is true, that item will be added to the new filtered collection. As an example, in vanilla JavaScript we could do the following:
constcandidates=[{name:"James",age:26},{name:"Dave",age:21},{name:"Sally",age:15},{name:"Marc"}];functioncandidateAgeFilterFn(candidate){returncandidate.age&&candidate.age>=16;}consteligableForDrivingTest=candidates.filter(candidateAgeFilterFn);console.log(eligableForDrivingTest);// [ { name: 'James', age: 26 }, { name: 'Dave', age: 21 } ]
Our aim is to implement a customfilter
function to replicate this behaviour.
Tests
describe('filter',()=>{it('should apply the condition correctly',()=>{constcollection=[-1,2,-3];constfilterFn=item=>item>0;constactual=filter(collection,filterFn);constresult=[2];expect(actual).toStrictEqual(result);});});
Generally we just need to test that given a collection and a predicate, the subset is returned as expected. Just likeour article about array map, filter is a generally simple implementation to achieve as we will see later in the next section of this article and thus this test is enough for now to use as a proof.
Implementation
The nativefilter
function has the following signature:
letnew_array=arr.filter(functioncallback(currentValue[,index[,array]]){// return element for new_array}[,thisArg])
We will aim to reproduce this behaviour with the following implementation:
/** * @function filter * @description A function to filter a collection via a filtering function * @param {Array} collection - The collection to filter * @param {Function} filterFn - When this function returns true, the item is added to the final output collection * @returns {Array} The filtered collection */functionfilter(collection,filterFn){constoutput=[];constclone=[...collection];for(letindex=0;index<clone.length;index++){constitem=clone[index];constcondition=filterFn(item,index,clone);if(condition===true){output.push(item);}}returnoutput;}
We instantiate two arrays in the function body, the first will be ouroutput
array and the second is a clone of thecollection
array. As withour article about array map we clone thecollection
since we will pass this clone into the providedfilterFn
and if the user decides to alter the array reference, the initialcollection
will not have mutated, only the clone. Next we loop each item in the cloned collection and run thefilterFn
, being sure to pass in theitem
,index
andcloned
array to match the native implementation. Finally we check if thefilterFn
returns true and if so, we add the current item to theoutput
array. Once every item has been looped over and filtered we return theoutput
.
Using our example of the native implementation near the top of this article, we could do the following to achieve the same results:
constcandidates=[{name:"James",age:26},{name:"Dave",age:21},{name:"Sally",age:15},{name:"Marc"}];functionfilter(collection,filterFn){constoutput=[];constclone=[...collection];for(letindex=0;index<clone.length;index++){constitem=clone[index];constcondition=filterFn(item,index,clone);if(condition===true){output.push(item);}}returnoutput;}functioncandidateAgeFilterFn(candidate){returncandidate.age&&candidate.age>=16;}consteligableForDrivingTest=filter(candidates,candidateAgeFilterFn);console.log(eligableForDrivingTest);// [ { name: 'James', age: 26 }, { name: 'Dave', age: 21 } ]
Conclusions
Hopefully this article gave you some insight into how the nativefilter
function works in languages like JavaScript. PHP usesarray_filter(collection, filterFn)
, Python usesfilter(filterFn, collection)
, etc. You can see the similarities of these and so with your new understanding of the mechanics at play, go and experiment and see what you can make happen. Re-invent the wheel and gain a deeper understanding of your tools and it'll help you going forward with your craft.
Top comments(2)

- LocationMünchen, Deutschland 🇩🇪
- EducationThe Open University
- WorkEngineering Manager @ Deutsche Fintech Solutions GmbH
- Joined
Note that that’s intentional.
For further actions, you may consider blocking this person and/orreporting abuse