简体   繁体   English

比较两个 arrays 并返回一个新数组,其中包含仅在原始 arrays 之一中找到的任何项目

[英]Compare two arrays and return a new array with any items only found in one of the original arrays

["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"] , ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"]

["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["pink wool"] . ["diorite", "andesite", "grass", "dirt", "dead shrub"]应该返回["pink wool"]

Because "pink wool is not present in first array ie arr1.But it is returning an empty array.This code is working fine with numbers only Array.But when array includes only string or strings with numbers the code does not work.因为“粉色羊毛不存在于第一个数组中,即 arr1。但它返回一个空数组。此代码仅适用于数字数组。但当数组仅包含字符串或带有数字的字符串时,代码不起作用。

function diff(arr1, arr2) {

    var newArray = arr2.concat(arr1);  //first joininng both arrays inn one and storing it in newArray 

    var newestArray = [];

    for (var i=0 ; i<newArray.length ; i++) {  //NOW COMPARING EACH ELEMENT OF  newArray  WITH ARR1 AD ARR2 AND PUSHING NOT SAME VALUES TO newestArray
        if (arr1.indexOf(newArray[i]) == -1) {
            newestArray.push(newArray[i]);

            if (arr2.indexOf(newArray[i]) == -1) {
                newestArray.push(newArray[i]);
            }
        }
    }

    return newestArray.filter(Boolean);   //It is returning an empty arrray but it should return "pink wool"
}

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

This Solution has a linear approach with an object for counting.此解决方案具有用于计数的对象的线性方法。

 var array1 = ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], array2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"]; function symmetricDifference(setA, setB) { var o = {}, result = []; function count(i, o) { return function (a) { o[a] = o[a] || { count: 0, value: a }; o[a].count += i; }; } setA.forEach(count(1, o)); setB.forEach(count(-1, o)); Object.keys(o).forEach(function (k) { if (o[k].count) { o[k].count = Math.abs(o[k].count); while (o[k].count--) { result.push(o[k].value); } } }); return result; } document.write('<pre>' + JSON.stringify(symmetricDifference(array1, array2), 0, 4) + '</pre>');

Guys thanks a lot for your help but when a person is asking a question like mine,we are not asking for a brand new solution for our problem.That will be clear cut copying and what will I learn from that?伙计们非常感谢您的帮助,但是当有人问像我这样的问题时,我们并不是在为我们的问题寻求全新的解决方案。那将是清晰的复制,我将从中学到什么? What about all the time I put to solve my problem.My solution can be corrected,I need to solve that thing,so that I don't repeat such mistake and can learn where I was wrong.我一直在解决我的问题呢?我的解决方案可以被纠正,我需要解决那个问题,这样我就不会重复这样的错误,并且可以知道我错在哪里。

I found out there was a very silly mistake of braces only and that solved my whole problem.我发现只有大括号有一个非常愚蠢的错误,这解决了我的整个问题。

function diff(arr1, arr2) {

    var newArray = arr2.concat(arr1);  //first joininng both arrays inn one and storing it in newArray 

    var newestArray = [];

    for (var i=0 ; i<newArray.length ; i++) {  //NOW COMPARING EACH ELEMENT OF  newArray  WITH ARR1 AD ARR2 AND PUSHING NOT SAME VALUES TO newestArray
        if (arr1.indexOf(newArray[i])===-1) {
            newestArray.push(newArray[i]);
        }  //Solution to my problem,I put this braces after the next if, because of that next if was not running. 

        if (arr2.indexOf(newArray[i])===-1) {
            newestArray.push(newArray[i]);
        }
    }

    return newestArray;   //It is returning an empty arrray but it should return "pink wool"
}

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

For ES6, with Set as following.对于 ES6, Set如下。

function diff(arr1, arr2) {
    var s1 = new Set(arr1);
    var s2 = new Set(arr2);

    for (let item of s1) {
        if (s2.has(item)) {
            s2.delete(item);
            s1.delete(item);
        }
    }

    return Array.from(s1).concat( Array.from(s2) );
    //return [...s1].concat([...s2]);
}

You can check the arrays by using a Array.forEach loop and Array.indexOf .您可以使用Array.forEach循环和Array.indexOf检查数组。

We loop the largest array against the shortest array and then to make sure you get also the values that are single to each array, you can index which matches you found, and then add the items that weren't found in the shortest array.我们将最大数组与最短数组循环,然后确保您也获得每个数组的单个值,您可以索引找到的匹配项,然后添加在最短数组中未找到的项目。

 'use strict'; var arr1 = ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub", "alpha"], arr2 = ["diorite", "andesite", "grass", "dirt", "dead shrub", "beta"]; function compare(left, right) { if (!left || !left.length) { return right; } if (!right || !right.length) { return left; } var i, len, source, target, value, result = [], indexes = {}; // swap to make sure we iterate the longest array if (left.length > right.length) { source = left; target = right; } else { target = left; source = right; } source.forEach(function(item) { var index = target.indexOf(item); if (index >= 0) { indexes[index] = true; return; } result.push(item); }); for (i = 0, len = target.length; i < len; i++) { if (!indexes[i]) { result.push(target[i]); } } return result; } console.log(compare(arr1, arr2)); console.log(compare(arr2, arr1));

It's just you need to find diff between two arrays:只是你需要找到两个数组之间的差异:

let diff = (a, b) => a.filter(x => b.indexOf(x) === -1);
let fullDiff = (a, b) => diff(a, b).concat(diff(b, a));


/*
    var a = ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"]
    var b = ["diorite", "andesite", "grass", "dirt", "dead shrub"]
    fullDiff(a,b) // ["pink wool"]
*/

Or in ES5:或者在 ES5 中:

var diff = function(a, b) {
    return a.filter(function(value) { return b.indexOf(value) === -1; });
},

fullDiff = function(a, b) {
    return diff(a, b).concat(diff(b, a));
};

PS If the arrays is really big or it's in a performance-critical part of the system, it's better to use less complex approach (in terms of big-O). PS 如果数组真的很大或者它在系统的性能关键部分,最好使用不太复杂的方法(就 big-O 而言)。

function diffArray(arr1, arr2) {
  return arr1.concat(arr2).filter(
    item => !arr1.includes(item) || !arr2.includes(item)
  )
}
diffArray(["df","sds","sdsd",], ["as","as","as"]);

This is a straight-forward example, replacing the duplicate values with 'x' and filtering them out:这是一个直截了当的示例,用“x”替换重复值并将它们过滤掉:

function diffArray(arr1, arr2) {
var newArr = [];
var result = [];
var array1 = arr1;
var array2 = arr2;
//a nested loop to replace duplicate values with 'x'
for (var i = 0; i < arr1.length; i++){
  for (var j = 0; j < arr2.length; j++) {
    if (array1[i] == array2[j]){
    array1.splice(i, 1, 'x');
    array2.splice(j, 1, 'x');
          }
      }
  }

newArr = array1.concat(array2);

//remove the 'x's
for (var k = 0; k < newArr.length; k++) {
  if (newArr[k] != 'x') {
    result.push(newArr[k]);
        }
    }

  return result;
}

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

To me is much easier!对我来说容易多了!

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

  function isIn(value){
     if (arr2.indexOf(value) === -1){
        return true;  
     }
     arr2.splice(arr2.indexOf(value), 1); 
  }

  newArr = arr1.filter(isIn);

  return newArr.concat(arr2);
}

filter and indexOf makes most of the work, and splice give us the rest of the element not matched so it wont be neccessary to check if an array is bigger than other! filter 和 indexOf 完成了大部分工作,而 splice 为我们提供了其余未匹配的元素,因此无需检查数组是否比其他数组大! Good luck!祝你好运!

I think this is easier to understand我认为这更容易理解

function diffArray(arr1, arr2) {

    var newArray = [];

    var condition1 =  arr1.forEach(function(x) {
        if(!arr2[arr2.indexOf(x)]) {
            newArray.push(x);
        }
    });

    var condition2 = arr2.forEach(function(y){
        if(!arr1[arr1.indexOf(y)]) {
            newArray.push(y);
        }
    });


    var compare = arr1.length > arr2.length ? condition1 : condition2;

    return newArray;
}

You can use lodash for this https://lodash.com/docs/4.17.4#difference您可以为此使用 lodash https://lodash.com/docs/4.17.4#difference

use _.difference(array, [values]) to find the differences between two array values使用 _.difference(array, [values]) 查找两个数组值之间的差异

_.difference([2, 1], [2, 3]); _.difference([2, 1], [2, 3]); // => [1] // => [1]

If you want to check differences on more parameters you can use differenceWith or differenceBy.如果您想检查更多参数的差异,您可以使用 differenceWith 或 DifferenceBy。

_.differenceWith(array, [values], [comparator]) https://lodash.com/docs/4.17.4#differenceWith _.differenceWith(数组,[值],[比较器]) https://lodash.com/docs/4.17.4#differenceWith

.differenceBy(array, [values], [iteratee= .identity]) https://lodash.com/docs/4.17.4#differenceBy .differenceBy(array, [values], [iteratee= .identity]) https://lodash.com/docs/4.17.4#differenceBy

This is a neat way to solve this problem:这是解决此问题的一种巧妙方法:

function diffArray(arr1, arr2) {
  var newArray = arr1.concat(arr2);

  function find(item) {
    if (arr1.indexOf(item) === -1 || arr2.indexOf(item) === -1) {
      return item;
    }
  }

  return newArray.filter(find);
}

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

Longer answer but logic well broken down.更长的答案,但逻辑很好地分解了。

 function diffArray(arr1, arr2) { var newArrUn; // Same, same; but different. if (arr2.length >= arr1.length) { var newArr = []; var newArrY = []; var UnusualElement = []; var UnusualElementY = []; for (var i = 0; i < arr2.length; i++) { newArr[i] = arr1.indexOf(arr2[i]); } for (var t = 0; t < arr1.length; t++) { newArrY[t] = arr2.indexOf(arr1[t]); } for (var j = 0; j < newArr.length; j++) { if (newArr[j] === -1) { UnusualElement[j] = arr2[j]; } } for (var e = 0; e < newArrY.length; e++) { if (newArrY[e] === -1) { UnusualElementY[e] = arr1[e]; } } return (UnusualElement.filter(Boolean)).concat(UnusualElementY.filter(Boolean)); } else { if (arr1.length >= arr2.length) { var newArrX = []; var newArrXX = []; var UnusualElementX = []; var UnusualElementXX = []; for (var b = 0; b < arr1.length; b++) { newArrX[b] = arr2.indexOf(arr1[b]); } for (var u = 0; u < arr2.length; u++) { newArrXX[u] = arr1.indexOf(arr2[u]); } for (var x = 0; x < newArrX.length; x++) { if (newArrX[x] === -1) { UnusualElementX[x] = arr1[x]; } } for (var z = 0; z < newArrXX.length; z++) { if (newArrXX[z] === -1) { UnusualElementXX[z] = arr2[z]; } } return (UnusualElementX.filter(Boolean)).concat(UnusualElementXX.filter(Boolean)); } } }

function diffArray(arr1, arr2) { 
    var newArr = []; // Same, same; but different. 

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

    for(let i = 0; i< arr2.length;i++) { 
        if(arr1.indexOf(arr2[i])==-1) { 
            newArr.push(arr2[i]); 
        } 
    } 
    return newArr; 
} 
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

这是我对上述问题的解决方案

function diffArray(arr1, arr2) { let newArray = arr1.concat(arr2) return newArray.filter(item => !(arr1.includes(item) && arr2.includes(item))) }

 function diffArray(arr1, arr2) { const newArr = []; for (let item of arr1){if (arr2.indexOf(item)==-1) newArr.push(item);} for (let item of arr2){if (arr1.indexOf(item)==-1) newArr.push(item);} return newArr; } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

暂无
暂无

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

相关问题 比较对象的 arrays 并返回不在 arrays 之一中的新对象数组 - Compare arrays of objects and return new array of objects that are not in one of the arrays Javascript比较两个不同大小的数组,并返回不在第二个数组中的项目 - Javascript Compare two arrays with different sizes and return the items that are not in second array 比较两个 Arrays 对象,如果 Javascript 中的值为真,则返回一个新数组 - Compare Two Arrays Of Objects and return a new array if value is true in Javascript 根据ID比较两个数组,然后根据值返回一个新数组 - compare two arrays based on a id and return a new array based on values 对于两个数组,查找仅存在于一个数组中的项目(对称差异) - For two arrays find items that are present in one array only (symmetric difference) 如何深入比较两个javascript对象并返回所有差异,包括新添加的数组和相同的原始格式? - How to deep compare two javascript objects and return all the differences including new added arrays and with the same original format? 如何比较两个 arrays 并返回另一个? - How to compare two arrays and return another one? 比较两个数组并追加到新数组 - Compare two arrays and append to new array 试图比较两个对象的 arrays 并从一个数组中删除匹配的元素并返回它,目前只删除第一个匹配项 - Trying to compare two arrays of objects and remove matching elements from one array and return it, currently only removing first match 如何比较两个对象数组,如果第二个数组项值如此说明,则仅从第一个数组中删除项 - How to compare two arrays of objects and only remove items from 1st array if 2nd arrays item value says so
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM