JavaScript Nuggets — Filter & Find

Ceren Şolpan Türe
1 min readJul 28, 2021

In this story which is the second of this series, I will explain filter() and find() methods.

Filter returns a new array. The difference from map() method is can manipulate the size of the new array. If there are no matches according to condition, returns an empty array.

const people = [
{
name: 'Ceren',
age: 29
},
{
name:'Esra',
age:34
},
{
name:'Aslı',
age:20
}
];
const young= people.filter((person)=>{
return person.age <30;
});
console.log(young); //[{name:'Ceren',age:29},{name:'Aslı',age:20}]
// no match
const name= people.filter((person)=> person.name === 'Seda';
);
console.log(name); //[]

Find method returns a single object and first match according to condition. If there are no matches, returns undefined.

const people = [
{
name: 'Ceren',
age: 29
},
{
name:'Esra',
age:34
},
{
name:'Aslı',
age:20
}
];
// first match
const young= people.find((person)=>{
return person.age <30;
});
console.log(young); //{name:'Ceren',age:29}
// no match
const name= people.find((person)=> person.name === 'Seda';
);
console.log(name); //undefined
const animals= ['dog','duck','giraffe','camel'];
const animal= animals.find((animal)=> animal === 'giraffe');
console.log(animal); // giraffe

I tried to explain filter() and find() methods which are the JavaScript methods. If you want to see more details, you can review my codes on my Github profile.

If I have any mistakes, please feedback to me.

Thank You!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/cerensolpan/

GitHub: https://github.com/cerensolpan

--

--