【问题标题】:How to compare objects within an Array and output non matching object如何比较数组中的对象并输出不匹配的对象
【发布时间】:2020-12-03 13:29:14
【问题描述】:

如何比较数组中的对象并输出字段值与其他对象不匹配的对象(忽略 id 字段)。这将如何在 Javascript、ES6 或 Lodash 中完成?

你应该知道的事情:输入数组应该是任意长度,对象可以有其他字段但在比较时被忽略。应该输出奇数的对象,或者如果没有多数则输出所有的对象。

const array1 = [{_id:'1', cow: true, sheep: true, pig: false}, 
               {_id:'2', cow: false, sheep: true, pig: true}, 
               {_id:'3', cow: true, sheep: true, pig: false}]

const array2 = [{_id:'1', cow: true, sheep: true, pig: false}, 
                {_id:'2', cow: false, sheep: true, pig: true}, 
                {_id:'2', cow: false, sheep: true, pig: true},
                {_id:'3', cow: true, sheep: true, pig: false}]

// expected array1 outcome:
{_id:'2', cow: false, sheep: true, pig: true}

// expected array2 outcome:
[{_id:'1', cow: true, sheep: true, pig: false}, 
 {_id:'2', cow: false, sheep: true, pig: true}, 
 {_id:'2', cow: false, sheep: true, pig: true},
 {_id:'3', cow: true, sheep: true, pig: false}]

【问题讨论】:

    标签: javascript arrays object lodash


    【解决方案1】:
    function diff(array) {
      const m = new Map();
    
      for (const {cow, sheep, pig} of array) {
        const str = `${cow}${sheep}${pig}`;
        m.set(str, (m.get(str) || 0) + 1);
      }
      
      const result = [];
      for (let i = 0; i < array.length; i++) {
        const {cow, sheep, pig} = array[i];
        const str = `${cow}${sheep}${pig}`;
        if (m.get(str) == 1) {
          result.push(array[i])
        }
      }
    
      if (result.length) {
        return result;
      }
      return array;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多