I have an array of objects. I need to write a function that will search the array by properties/values passed as param object. So for example I have this array of users:
const items = [{
firstName:"John",
lastName: 'Doe',
password: '*******',
email: '[email protected]',
role: 'ROLE_ADMIN'
},
{
firstName:"Jane",
lastName: 'Doe',
password: '********',
email: '[email protected]',
role: 'ROLE_USER'
},
{
firstName:"John",
lastName: 'Roe',
password: '**********',
email: '[email protected]',
role: 'ROLE_USER'
}]
Given I pass to the function the following param
{firstName: 'John'}
I should return an array of 2 objects for both users with the name John. And if I pass this param:
{firstName: 'John', role: 'ROLE_ADMIN'}
then I should return an array with only 1 user (in this case) which matches both params.
If no matching users found - return an empty array. If params is an empty object - return the entire array.
So I wrote this function:
findMany(params) {
return new Promise((resolve, reject) => {
const keys = Object.keys(params)
if (!keys.length || !this.items.length) return resolve(this.items)
let result = []
let isMatch = false
for (const item of this.items) {
for (const key of keys) {
if(item[key] === params[key]) {
isMatch = true
} else {
isMatch = false
}
if (!isMatch) break
}
if (isMatch) result.push(item.toJSON())
}
resolve(result)
})
}
Though it works just fine and I do get the desired result, I was wondering is there a more elegant way to write this? It kinda bugs me to have a nested loop, which increases the time complexity to O(n2). So is there a more elegant solution?
And I still didn't care of a case when someone may pass a property that doesn't exist, i.e.
{firstName: 'John', role: 'ROLE_ADMIN', someProperty: 'some value'}
Not sure how to tackle it...
O(n^2)only when it's looping twice over the same dataset. Therefore, for a dataset of sizenit will check every element a number of times equal ton. Having two loops over two different things is notn^2- at worse it'sO(n*m)(here that being the number of properties to check) butmmight be not very relevant. If you only check 1-3 properties, then the complexity still scales mostly with the number of elements -n.