简体   繁体   English

比较两个不同长度的数组,并返回包含不常见元素的数组

[英]comparing two arrays of different lengths and returning an array with the uncommon elements

Here, I have two arrays of different lengths.And an array is to be returned with the values which are uncommon in both the arrays.But the compiler is giving wrong output.What are the issues with these functionalities? 在这里,我有两个长度不同的数组,一个数组要返回的值在两个数组中都不常见,但是编译器输出错误,这些功能有什么问题? Output:[4,5] in this case instead of [4]. 输出:在这种情况下是[4,5],而不是[4]。

function diffArray(arr1, arr2) {
  var newArr = [];
  var y=[];
  var z=[];
  // Same, same; but different.
  var flag=0;
  for(var i=0;i<arr1.length;i++){
    if(arr2.indexOf(arr1[i]===-1)){
      z=arr1.slice(i,i+1);
      //return z;
    }
    for(var j=0;j<arr2.length;j++){
      if(arr1.indexOf(arr2[j])===-1){
        y=arr2.slice(j,j+1);
        //z=arr1.slice(i,i+1);
        //break;
      }
    }
  }
   return newArr.concat(y,z);
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

Try the following: 请尝试以下操作:

function diffArray (arr1, arr2) {
    var z = arr1.filter(function (value) { return !~arr2.indexOf(value); });
    var y = arr2.filter(function (value) { return !~arr1.indexOf(value); });

    return [].concat(y, z);
}

You can try an alternative for your function 您可以尝试替代功能

a1 = [1, 2, 3, 5];
a2 = [1, 2, 3, 4, 5];
result = [];
if (a1.length > a2.length) {
  temp = a1;
  a1 = a2;
  a2 = temp;
}

$.grep(a2, function(k) {
        if ($.inArray(k, a1) == -1) result.push(k);
});
console.log(result);,

Here is working jsfiddle for your both array sets. 这是两个数组集都可以使用的jsfiddle

Give it a try, this will work. 试试看,这将起作用。

In your code you have lines like: 在您的代码中,您有如下几行:

z=arr1.slice(i,i+1);
y=arr2.slice(j,j+1);

If you do so, each time you get a unique element, you will lose the previous one stored. 如果这样做,则每次获得唯一元素时,都会丢失之前存储的元素。

Also, Array.prototype.slice returns an array, therefore you don't need to use slice() as well. 同样, Array.prototype.slice返回一个数组,因此您也不需要使用slice()

function diffArray(arr1, arr2) {
  var newArr = [];
  var y=[];
  var z=[];

  var flag=0;
  for(var i=0;i<arr1.length;i++) {
    if(arr2.indexOf(arr1[i])===-1) {
      z.push(arr1[i]);
    }
  }

  for(var j=0;j<arr2.length;j++) {
    if(arr1.indexOf(arr2[j])===-1) {
      y.push(arr2[j]);
    }
  }

  return y.concat(z);
}

This should help you there. 这应该可以帮助您。

Here is a fiddle to show the same. 这是一个显示相同内容的小提琴

function diffArray(arr1, arr2) {
  var newArr = [];

  var firstArray = arr1;
  var secondArray = arr2;
  if (arr2.length > arr1.length) {
    firstArray = arr2;
    secondArray = arr1;
  }

  var isNotMatched = false;

  for (var i in firstArray) {
    for (var j in secondArray) {
      if (firstArray[i] !== secondArray[j]) {
        isNotMatched = true;
      } else {
        isNotMatched = false;
        break;
      }

    }

    if (isNotMatched)
      newArr.push(firstArray[i]);

  }

  return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

2nd version work for all 第2版​​适用于所有人

function diffArray(arr1, arr2) {
  var newArr = [];
  var firstArray = arr1;
  var secondArray = arr2;
  if (arr2.length > arr1.length) {
    firstArray = arr2;
    secondArray = arr1;
  }

  var whenSameLegth = '';
  var isNotMatched = false;

  for (var i in firstArray) {
    for (var j in secondArray) {
      if (firstArray[i] !== secondArray[j]) {
        isNotMatched = true;
        whenSameLegth = secondArray[j];
      } else {
        isNotMatched = false;
        break;
      }

    }
    if (isNotMatched && arr2.length === arr1.length) {
      newArr.push(firstArray[i]);
      newArr.push(whenSameLegth);
    } else if (isNotMatched) {
      newArr.push(firstArray[i]);
    }
  }

  return newArr;
}

diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]); diffArray([[“ andesite”,“ grass”,“ dirt”,“ pink wool”,“ dead shrub”],[“ diorite”,“ andesite”,“ grass”,“ dirt”,“ dead shrub”]));

The code, as written, can only return up to two items, because y and z are always overwritten with a new array of length one whenever z=arr1.slice(i,i+1); 编写的代码最多只能返回两项,因为每当z=arr1.slice(i,i+1); yz总是被长度为1的新数组覆盖z=arr1.slice(i,i+1); or y=arr2.slice(j,j+1); y=arr2.slice(j,j+1); are called. 叫做。 You probably want to use Array.push, ie z.push(arr1[i]); 您可能要使用Array.push,即z.push(arr1[i]); and y.push(arr2[j]); y.push(arr2[j]); . This will add to the same array each time an element is found, rather than reset the result array each time. 每次找到一个元素时,它将添加到同一数组中,而不是每次都重置结果数组。

You can merge both array and return unique values. 您可以合并两个数组并返回唯一值。

 function diffArray(a1, a2){ var data = a1.concat(a2); return data.filter(function(item, i, a){ return a.indexOf(item) === a.lastIndexOf(item) }); } console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])); console.log(diffArray([1, 2, 3, 5], [11, 12, 13, 14, 5])); 

Try this 尝试这个

var newArr = [];
    function diffArray(arr1, arr2) {


            arr1.forEach(function (item) {
                if (arr2.indexOf(item) === -1)
                    newArr.push(item);
            });

            arr2.forEach(function (item) {
                if (arr1.indexOf(item) === -1)
                    newArr.push(item);
            });

    }

    diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

If you can use the latest version of JavaScript (ES6), the following should do the trick and run in linear time as opposed to quadratic time — O(N) vs. O(N²). 如果您可以使用最新版本的JavaScript(ES6),则可以使用以下技巧,并以线性时间而不是二次时间运行-O(N)vs. O(N²)。

 function diffArray(a, b) { a = new Set(a) let result = [] for (let value of b) { a.delete(value) || result.push(value) } result.push(...a) return result } console.log(diffArray( [1, 2, 3, 5], [1, 2, 3, 4, 5] )) console.log(diffArray( ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] )) 

You could use a hash table and count the occurence. 您可以使用哈希表计算发生的次数。 it works for more than one equla element in an array as well. 它也适用于数组中的多个equla元素。

 function getSymmetricDifference(a1, a2) { var hash = {}; a1.forEach(function (a) { (hash[a] = hash[a] || { count: 0, value: a }).count++; }); a2.forEach(function (a) { (hash[a] = hash[a] || { count: 0, value: a }).count--; }); return Object.keys(hash).filter(function (a) { return hash[a].count; }).map(function (a) { return hash[a].value; }); } console.log(getSymmetricDifference([1, 2, 3, 5], [1, 2, 3, 4, 5])); console.log(getSymmetricDifference(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"])); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM