I want to create a function to compare a list of objects in the fast way
for (let i = 0; i < posts.length - 1; i++) {
for (let j = i + 1; j < posts.length; j++) {
const post1 = posts[i];
const post2 = posts[j];
if (validation(post1, post2)){
console.log(`found comparation`);
}
}
}
And the validation function compares two fields like this:
const validation = (post1, post2) => post1.need.includes(post2.have) &&
post2.need.includes(post1.have);
What would be the fastest way to perform this search? These ‘need’ and ‘have’ strings are IDs for a category where I associate them by levels like ‘01030204’. In case it’s useful to know, I’m open to dividing the data based on this, but I’m really looking for ideas on how to improve the speed of this search.
2
Answers
Maybe you can hash every object, and use a dictionary to decide whether a hash has a corresponding object. When the hash matches, you then do the real comparison. This should be able to do the job in O(n) time.
includes
is not an efficient method when you have to repeat it on the same array several times. Also, if you would key your data by thosehave
strings, and register for each of them which are theneed
strings that can be reached by which posts, then you have a more efficient adjacency list (graph data structure), and can hope to find such matching pairs faster.As you didn’t provide sample data, I had to invent some. Here is a possible implementation: