javascript - 尝试使用 Javascript 解决对称差异

标签 javascript arrays symmetric-difference

我正在尝试找出对称的解决方案 使用实现以下功能的 javascript 的区别 目标:

  • 接受未指定数量的数组作为参数
  • 保留数组中数字的原始顺序
  • 不删除单个数组中的重复数字
  • 删除数组中出现的重复项

因此,例如, 如果输入是 ([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]), 解决方案是 [1, 1, 6, 5, 4]。

我正在尝试解决这个在线挑战 编码社区。挑战的确切说明 状态,

Create a function that takes two or more arrays and returns an array of the symmetric difference of the provided arrays.

The mathematical term symmetric difference refers to the elements in two sets that are in either the first or second set, but not in both.

虽然我下面的解决方案找到了数字 每个数组都是唯一的,它消除了所有出现的数字 不止一次并且不保持数字的顺序。

我的问题与在 finding symmetric difference/unique elements in multiple arrays in javascript 上提出的问题非常接近.然而,解决方案 不保留数字的原始顺序,也不保留单个数组中出现的唯一数字的重复项。

function sym(args){
    var arr = [];
    var result = [];
    var units;
    var index = {};
    for(var i in arguments){
        units = arguments[i];

    for(var j = 0; j < units.length; j++){
         arr.push(units[j]);
        }
    }

    arr.forEach(function(a){
        if(!index[a]){
            index[a] = 0;
        }
            index[a]++;

    });

       for(var l in index){
           if(index[l] === 1){
               result.push(+l);
           }
       }

    return result;
}
symsym([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]); // => Desired answer: [1, 1, 6. 5. 4]

最佳答案

与所有问题一样,最好从编写算法开始:

Concatenate versions of the arrays, where each array is filtered to contain those elements which no array other than the current one contains

然后用 JS 写下来:

function sym() {
  var arrays = [].slice.apply(arguments);

  return [].concat.apply([],               // concatenate
    arrays.map(                            // versions of the arrays
      function(array, i) {                 // where each array
        return array.filter(               // is filtered to contain
          function(elt) {                  // those elements which
            return !arrays.some(           // no array
              function(a, j) {             // 
                return i !== j             // other than the current one
                  && a.indexOf(elt) >= 0   // contains
                ;
              }
            );
          }
        );
      }
    )
  );
}

非注释版本,使用 ES6 编写得更简洁:

function sym(...arrays) {
  return [].concat(arrays . 
    map((array, i) => array . 
      filter(elt => !arrays . 
        some((a, j) => i !== j && a.indexOf(elt) >= 0))));
}

关于javascript - 尝试使用 Javascript 解决对称差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30834946/

相关文章:

javascript - 构造函数与闭包?

arrays - 如何指定任意嵌套长度的嵌套数组的返回类型?

arrays - 是否有一种正确的方法可以在引用一维中转换二维数组

python-3.x - python : Symmetrical Difference Between List of Sets of Strings

javascript - 当我们有多个 setTimeouts 时,javascript 事件队列如何工作

javascript - jquery 函数调用不起作用

javascript - 为数组的每个值返回 NAN

Python 设置 : difference() vs symmetric_difference()

python-3.x - 如何获得两个列表之间的对称差异?

javascript - Three.js OBJ MTL 加载器在 IOS 上不可见