1
\$\begingroup\$

I got an initial array, I am checking against another array to find how many objects have at least one instance of the Domain in data.

I wonder if there is a more performant way to achieve the same goal.

const data = [
 {
 Domain: 'google.com',
 '# Reocurring Domains': 0
 },
 {
 Domain: 'apple.com',
 '# Reocurring Domains': 0
 },
 {
 Domain: 'facebook.com',
 '# Reocurring Domains': 0
 }
]
const domains = [
 {
 'google.com': true,
 'microsoft.com': true,
 'google.com': true
 },
 {
 'apple.com': true,
 'microsoft.com': true,
 'twitter.com': true
 },
 {
 'facebook.com': true,
 'apple.com': true,
 'facebook.com': true
 }
]
for (const obj of data) {
 let count = 1
 for (const entry of domains) {
 if (entry[obj.Domain]) {
 obj['# Reocurring Domains'] = count++
 }
 }
}
console.log(data)

In there any way to this with a more performant approach?

Chocolate
1,0145 silver badges21 bronze badges
asked Feb 16, 2021 at 16:25
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

You could create a look up table (a simple object) where you can pre calculate the amount of times a domain is in the repeated in the domains array, this reduces the algorithmic complexity of your current solution which is n * m (dataElements * domainElements)

Whereas my suggestion has a lower complexity of (n + m)

const data = [
 {
 Domain: 'google.com',
 '# Reocurring Domains': 0
 },
 {
 Domain: 'apple.com',
 '# Reocurring Domains': 0
 },
 {
 Domain: 'facebook.com',
 '# Reocurring Domains': 0
 }
]
const domains = [
 {
 'google.com': true,
 'microsoft.com': true,
 'google.com': true
 },
 {
 'apple.com': true,
 'microsoft.com': true,
 'twitter.com': true
 },
 {
 'facebook.com': true,
 'apple.com': true,
 'facebook.com': true
 }
]
const domainsObj = {}
domains.forEach(domain => {
 Object.keys(domain).forEach(key => key in domainsObj ? domainsObj[key] += 1: domainsObj[key] = 1)
})
data.forEach(element => element['# Reocurring Domains'] = domainsObj[element.Domain]);
console.log(data);

This approach increases memory usage, but improves calculation speed.

answered Feb 16, 2021 at 22:48
\$\endgroup\$
2
  • \$\begingroup\$ Thanks Daniel, when I check in jsbench, it says otherwise jsbench.me/7lkl9a1bf5/2 \$\endgroup\$ Commented Feb 17, 2021 at 10:15
  • \$\begingroup\$ Well for a small amount of data it could be the case that this approach is not that good, but if we consider the case that your data is going to be large enough, this solution should be better :) \$\endgroup\$ Commented Feb 17, 2021 at 22:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.