通过检查两个元素从数组中获取重复值

时间:2018-05-16 05:54:11

标签: javascript arrays typescript ecmascript-6

如果我的数组有以下数据

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 },...]

然后我期待以下结果

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

如果我的数组有以下数据

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 },...]

然后我期待以下结果。

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

我尝试过这种方式: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);
&#13;
&#13;
&#13;

但无法获得重复的值。你能解决这个问题吗?

  

注意:如果SalseVersionMarketingCode值为string/number/Boolean,请注意它也应该正常工作。

因为我已经尝试了以下一些答案,我收到以下错误。

enter image description here

4 个答案:

答案 0 :(得分:5)

您可以使用reduce

第一个reduce会使用SalseVersionMarketingCode的连接值对值进行分组。

第二个reduce将检查该组是否包含多个元素。如果concat值为1个数组。

&#13;
&#13;
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 );
&#13;
&#13;
&#13;

答案 1 :(得分:2)

看起来您正在尝试查找阵列中至少有一个其他元素具有相似属性的元素。您可以使用.filter,然后使用sort

&#13;
&#13;
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}]))
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以将代码更新为以下

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

基本上cou可以继续排序,但是使用想要的键,这将返回一种分组数组,其中所有想要的键及其值都在直接邻域中。

然后你可以通过检查具有实际值的所有键以及前一个或后继者来过滤数组。

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

通过使用哈希表临时收集组的第一个对象或仅表示组的重复项,对未排序数据采用单循环方法。

&#13;
&#13;
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);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;