3

Its quite a simple problem but I am unable to figure out the logic.

I have Arr1 = [1,2,3,4] and Arr2 = [3,4,5,6]

I would like compare Arr2 with Arr1 and add missing values to MissingArr = [];

my code

let missing = [];  
 arrOfNum.forEach( (number) => {

  // Arr2 = 3,4,5,6
  console.log("number: "+number);
  for(let i = 0; i < this.numbers.length; i++){

      // Arr1 = 1,2,3,4
      console.log("this.numbers: "+this.numbers[i]['number']); 

      if(number == this.numbers[i]['number'])
      {
        //Do Nothing
      }else{
        missing.push(this.numbers[i]['number']);
      }
  }
});

I am not sure how to do a check of Arr2 to Arr1 (complete entire forloop) and only if Arr2 value does not exist in Arr1 then add it to missing array.

Update

Arr1 = [{id:1, number:1}, {id:2, number:2},{id:3, number:3}, {id:4, number:4}]
Arr2 = [3,4,5,6]

so missing array should be: Missing= [5,6]

4
  • Arr2.filter(e => !Arr1.includes(e));? Commented Jan 27, 2018 at 15:05
  • @NenadVracar I forgot to mention my Arr2 is just arr of numbers whereas Arr1 is Array of objects. will this still work? !Arr1['numbers'].includes(e) Commented Jan 27, 2018 at 15:10
  • Post your actual data. Commented Jan 27, 2018 at 15:10
  • @NenadVracar I have posted actual data to my updated section of the question Commented Jan 27, 2018 at 15:18

2 Answers 2

3

You can do this with filter and some methods.

const Arr1 = [{id:1, number:1}, {id:2, number:2},{id:3, number:3}, {id:4, number:4}],
Arr2 = [3,4,5,6]

const result = Arr2.filter(e => !Arr1.some(o => o.id == e));
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Array.filter to achieve this. Array.filter returns an array containing items matching the predicate.

var arr1 = [{key: 1},{key: 2},{key: 3},{key: 4}];
var arr2 = [3,4,5,6];

//This will return all values in array2 missing in array1
var missing = arr1.filter(function(arr1_item){
    return arr2.indexOf(arr1_item.key) === -1;
});

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.