Get duplicated values from an array by checking with two element

If My array have this below data

let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 13 },
        { name: "Siva", SalseVersion: 10, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 },...]

Then I am expecting this below result

[{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
 { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }]

If My array have this below data

let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 14},
        { name: "Siva", SalseVersion: 12, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 },...]

Then I am expecting this below result.

        [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }
        { name: "Suresh", SalseVersion: 12, MarketingCode: 14},
        { name: "Siva", SalseVersion: 12, MarketingCode: 14 }]

I have tried this way : Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

let arr = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 13 },
        { name: "Siva", SalseVersion: 10, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }]


var sorted_arr = arr.slice().sort();
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1].SalesVersion == sorted_arr[i].SalesVersion && sorted_arr[i + 1].MarketingCode == sorted_arr[i].MarketingCode) {
        results.push(sorted_arr[i]);
    }
}

console.log(results);

But unable to get the duplicated values. Could you please resolve this?

Note: Please mind it should be work as well if the SalseVersion and MarketingCode value is string/number/Boolean.

because I have tried some of the below answers and i am getting this below error.

enter image description here

4 answers

  • answered 2018-05-16 05:59 Nikhil Aggarwal

    You can update your code to following

    let arr = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },
        { name: "Suresh", SalseVersion: 12, MarketingCode: 14},
        { name: "Siva", SalseVersion: 12, MarketingCode: 14 },
        { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 },
        { name: "OP", SalseVersion: 10, MarketingCode: 11 }]
    
    // You need to write the custom sort function
    var sorted_arr = arr.slice().sort((a,b) => {
         if(a.SalseVersion === b.SalseVersion) {
              return a.MarketingCode- b.MarketingCode;
          }
          return a.SalseVersion - b.SalseVersion;
    });
    var results = [];
    for (var i = 0; i < sorted_arr.length - 1; i++) {
        if (sorted_arr[i + 1].SalesVersion == sorted_arr[i].SalesVersion && sorted_arr[i + 1].MarketingCode == sorted_arr[i].MarketingCode) {
            /* push both the elements in case of match with only exception 
             * being if it has been pushed previously where there are more than 2 matches */
           if (i >= 1 && sorted_arr[i - 1].SalesVersion == sorted_arr[i].SalesVersion && sorted_arr[i - 1].MarketingCode == sorted_arr[i].MarketingCode) {
             results.push(sorted_arr[i+1]);
           } else {
             results.push(sorted_arr[i], sorted_arr[i+1]);
           }            
        }
    }
    
    console.log(results);

  • answered 2018-05-16 06:01 CertainPerformance

    It looks like you're trying to find elements for which there exists at least one other element in the array with similar properties. You can use .filter for this, followed by sort:

    const dupesFromArr = array => {
      const filteredArr = array.filter(({ name, SalseVersion, MarketingCode }, i, arr) => (
        arr.find((item, findI) => (
          findI !== i &&
          SalseVersion === item.SalseVersion &&
          MarketingCode === item.MarketingCode
        ))
      ));
      return filteredArr.sort((a, b) =>
        String(a.SalseVersion).localeCompare(String(b.SalseVersion), 'kn') ||
        String(a.MarketingCode).localeCompare(String(b.MarketingCode), 'kn')
      );
    };
    
    console.log(dupesFromArr([{name:"Ramesh",SalseVersion:10,MarketingCode:11},{name:"Suresh",SalseVersion:12,MarketingCode:13},{name:"Siva",SalseVersion:10,MarketingCode:14},{name:"Sakthi",SalseVersion:10,MarketingCode:11}]))
    console.log(dupesFromArr([{name:"Ramesh",SalseVersion:10,MarketingCode:11},{name:"Suresh",SalseVersion:12,MarketingCode:14},{name:"Siva",SalseVersion:12,MarketingCode:14},{name:"Sakthi",SalseVersion:10,MarketingCode:11}]))

  • answered 2018-05-16 06:07 Eddie

    You can use reduce

    The first reduce will group the values using the concatenated values of SalseVersion and MarketingCode.

    The second reduce will check if the group has more than 1 element. If there is concat the values into 1 array.

    let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 },{ name: "Suresh", SalseVersion: 12, MarketingCode: 14},{ name: "Siva", SalseVersion: 12, MarketingCode: 14 },{ name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }];
    
    let result = Object.values(array.reduce((c, v) => {
      let k = v.SalseVersion + '-' + v.MarketingCode;
      c[k] = c[k] || [];
      c[k].push(v);
      return c;
    }, {})).reduce((c, v) => v.length > 1 ? c.concat(v) : c, []);
    
    console.log( result );

  • answered 2018-05-16 06:34 Nina Scholz

    Basically cou could keep sorting, but with the wanted key, this returns a kind of grouped array, where all wanted keys and their values ar in direct neighbourhood.

    Then you could filter the array by checking all keys with the actual value and the predecessor or the successor.

    var array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }],
        keys = ['SalseVersion', 'MarketingCode'],
        result = array
            .sort((a, b) => {
                var d;
                keys.some(k => d = a[k] - b[k]);
                return d;
            })
            .filter((o, i, a) => 
                keys.every(k => a[i - 1] && a[i - 1][k] === o[k]) ||
                keys.every(k => a[i + 1] && o[k] === a[i + 1][k])
            );
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    A single loop approach for unsorted data by using a hash table for temporary collecting the first object of a group or just to indicate duplicates of the group.

    var array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { name: "Sakthi", SalseVersion: 10, MarketingCode: 11 }],
        keys = ['SalseVersion', 'MarketingCode'],
        result = array.reduce((hash => (r, o) => {
            var key = keys.map(k => o[k]).join('|');
            if (key in hash) {
                if (hash[key]) {
                    r.push(hash[key]);
                    hash[key] = false;
                }
                r.push(o);
            } else {
                 hash[key] = o;
            }
            return r;
        })(Object.create(null)), []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }