0

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.

2 Answers 2

2

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]);    
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.