Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

James Robb
James Robb

Posted on • Edited on

     

Array filter

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 } ]
Enter fullscreen modeExit fullscreen mode

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);});});
Enter fullscreen modeExit fullscreen mode

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])
Enter fullscreen modeExit fullscreen mode

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;}
Enter fullscreen modeExit fullscreen mode

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 } ]
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ilya_sher_prog profile image
Ilya Sher
Ops, Dev, Management
  • Joined

Note thatcondition === true is different fromArray.prototype.filter() which checks forTruthy value

CollapseExpand
 
jamesrweb profile image
James Robb
I like to build cool things, work with nice people and help others where I can. Currently I'm an engineering manager for a fintech startup and historically a serial founder & freelancer software dev.
  • Location
    München, Deutschland 🇩🇪
  • Education
    The Open University
  • Work
    Engineering Manager @ Deutsche Fintech Solutions GmbH
  • Joined

Note that that’s intentional.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I like to build cool things, work with nice people and help others where I can. Currently I'm an engineering manager for a fintech startup and historically a serial founder & freelancer software dev.
  • Location
    München, Deutschland 🇩🇪
  • Education
    The Open University
  • Work
    Engineering Manager @ Deutsche Fintech Solutions GmbH
  • Joined

More fromJames Robb

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp