Search code examples
javascriptarraysobjectproxyinclude

How to merge the same items in the array using proxy?


I have 2 objects like this:

var customerA = {firstName: "Dravid, Tendulkar"},
    customerB = {firstName: "Virendra, Virat, Tendulkar"};

I want to find same names from those strings and merge them by using Proxy, but I can't go further more than this:

var customerA = {firstName: "Dravid, Tendulkar"},
    customerB = {firstName: "Virendra, Virat, Tendulkar"};

var proxyMerge = new Proxy([customerA, customerB], {
  get: (target, keyName) => {
    let arr = target.map(item => item[keyName]);
    let output = arr.filter(item => arr[item] == arr.includes(item)); // returns an empty array.
    return output;
  }
})

var customers = proxyMerge.firstName;
console.log(customers); // the output should be: ["Dravid, Tendulkar, Virendra, Virat"] 

How can I get a complete array has no same names?


Solution

  • Combine results from the map function. You'll have two strings as a result, so joining them to a single string and then splitting them back to a single array should do that.

    Then use a Set object to filter out any duplicates. A Set can only contain unique values, so any duplicate will not be added to the set. Then with the spread operator ... turn the Set back into an array and return that as an output.

    Now you'll have an array without any duplicate values.

    var customerA = {firstName: "Dravid, Tendulkar"},
        customerB = {firstName: "Virendra, Virat, Tendulkar"};
    
    var proxyMerge = new Proxy([customerA, customerB], {
      get: (target, keyName) => {
        let names = target.map(item => item[keyName]);
        let combined = names.join(', ').split(', ');
        let output = [...new Set(combined)];
        return output;
      }
    })
    
    var customers = proxyMerge.firstName;
    console.log(customers); // the output should be: ["Dravid, Tendulkar, Virendra, Virat"]