Member-only story

You may not know that JS native filter methods also have these problems

Beck Moulton
4 min readJul 10, 2023

--

In normal work, we will encounter various problems. One common problem is to filter out elements that meet specific conditions from a large array.

You may first think of the filter method provided natively by JS .

Indeed, filter is possible. So if you handle some complex filter conditions, JS native filter method still works?

JS native filter method

For example, we have a list of users, and each user has an active attribute that indicates whether the user is active or not. We can use the native JS method filter to find all eligible users.

const users = [
{ 'user': 'barney', 'active': true },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
const activeUsers = users.filter(user => user.active);console.log(activeUsers);
// output:[ { user: 'barney', active: true }, { user: 'pebbles', active: true } ]

Looking at this code, it is not difficult to find that the filter method allows us to easily filter the elements from the array that meet certain conditions. Although the native filter method can meet our needs, it also has some limitations.

Cannot handle null and undefined

Native filter methods may throw errors when dealing with null or undefined because they are not arrays and cannot call filter

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet