skip to Main Content

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


  1. const arr1 = [{name:'danny ro',age:14},{name:'Rose tl', age:17},{name:'Ali ga', age:15}]
    const arr2 =  [{name:'danny',class:'A'},{name:'Ron', class:'D'}]
    
    const filtered = arr2.filter(user => arr1.some(lookup => lookup.name.includes(user.name)));
    
    console.log(filtered);
    Login or Signup to reply.
  2. Cleaner method

    You can use Array.prototype.filter and Array.prototype.some to achieve this.

    Here’s how you could do this:

    const array1 = [
        {name:'danny ro', age:14},
        {name:'Rose tl', age:17},
        {name:'Ali ga', age:15}
    ];
    const array2 = [
        {name:'danny', class:'A'},
        {name:'Ron', class:'D'}
    ];
    
    // Create a new array 'result' that includes objects from array2 
    // if the 'name' of the object in array2 is included in the 'name' property of any object in array1
    const result = array2.filter(obj2 => 
        array1.some(obj1 => obj1.name.includes(obj2.name))
    );
    
    console.log(result);
    // [{ "name": "danny", "class": "A" }]
    

    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:

    const array1 = [
        {name:'danny ro', age:14},
        {name:'Rose tl', age:17},
        {name:'Ali ga', age:15}
    ];
    
    const array2 = [
        {name:'danny', class:'A'},
        {name:'Ron', class:'D'}
    ];
    
    // Create a name map from array1
    const nameMap = {};
    
    array1.forEach(obj => {
        const names = obj.name.split(' ');
        names.forEach(name => {
            nameMap[name] = true;
        });
    });
    
    // Filter array2 based on nameMap
    const result = array2.filter(obj2 =>
        nameMap[obj2.name]
    );
    
    console.log(result);
    // [{ "name": "danny", "class": "A" }]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search