简体   繁体   中英

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

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.

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.

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

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"]);

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); or y=arr2.slice(j,j+1); are called. You probably want to use Array.push, ie z.push(arr1[i]); and 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²).

 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.

 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"])); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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