Java script.
I have 2 arrays for example:
Array 1 [{name:'danny ro',age:14},{name:'Rose tl', age:17},{name:'Ali ga', age:15}]
Array 2 [{name:'danny',class:A},{name:'Ron', class:D}]
I want to compare only by names and to find out if array 1 has object with name that contains name from Array 2.
To my example I would get this answer :
{name:'danny',class:A}
I tried nesting loops but I’m looking for something simpler.
2
Answers
Cleaner method
You can use
Array.prototype.filter
andArray.prototype.some
to achieve this.Here’s how you could do this:
Efficient Method
To achieve this task with optimal efficiency, specifically adhering to
O(n)
time complexity, a mapping needs to be created using the names from the initial array.Here’s how you could do this: