简体   繁体   中英

Compare two array objects and find unique values

I have two objects which are arrays. I want to compare them and find unique values and assign them into another array. here is my code

function()
{
var input1 = [2,3,4,5];
var input2 = [2,3];
var arrayVal = [];
var res = input1.filter(function (n)
{
return input2.indexOf(n) == -1
}):
arrayVal.push(res);
console.log(arrayVal);
}

expected result is 4,5. But my output is 2,3,4,5.

Here is some old fashioned code which should work:

for (var i = 0; i < input1.length; i++){
   var found=false;
    for (var j = 0; j < input2.length; j++){
        if (input1[i]==input2[j]){
          found=true;
          break;
        }
   }
  if (!found)
    arrVal.push(input1[i]);    
}

There is a syntax error in your code.

return input2.indexOf(n) == -1
}): // <-- should be a semicolon

Your code looks mostly fine. The output is actually [[4, 5]] since you call arrayVal.push(res); . That line is pushing an array into another array, resulting in a nested array. You can use the spread syntax and avoid the nesting: arrayVal.push(...res); . After that, the output is [4, 5] .

Full code would be:

function()
{
  var input1 = [2,3,4,5];
  var input2 = [2,3];
  var arrayVal = [];
  var res = input1.filter(function (n)
  {
    return input2.indexOf(n) == -1
  });
  arrayVal.push(...res);
  console.log(arrayVal); // [4, 5]
}

And I'm sure your code is modified for the question, but there's no point in having both res and arrayVal here. You could refactor the code like so:

function() {
  var input1 = [2,3,4,5],
    input2 = [2,3];
  var input1SubtractInput2 = input1.filter(function(n) {
    return input2.indexOf(n) === -1
  });
  console.log(input1SubtractInput2); // [4, 5]
}

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-2024 STACKOOM.COM