1

How to compare two javascript arrays and create two new arrays of missing and new elements? Array elements will be always strings or numbers and it is not 100% sure that they will be sorted in any way.

var array1= ['11', '13', '14', '18', '22', '23', '25'];
var array2= ['11', '13', '15', '16', '17', '23', '25', '31'];
var missing_elements = [];
var new_elements = [];

***Required Output:***
missing_elements= ['14', '18', '22']
new_elements= ['15', '16', '17', '31']
Divya
  • 107
  • 1
  • 1
  • 7
  • Welcome to StackOverflow! Have you tried anything so far? StackOverflow isn't a free code-writing service, and expects you to [try to solve your own problem first](http://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried, showing the specific problem you are facing in a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). For further information, please see [how to ask a good question](http://stackoverflow.com/help/how-to-ask), and take the [tour of the site](http://stackoverflow.com/tour) – Jaromanda X Sep 11 '17 at 03:46

1 Answers1

2

Well a simple solution is just to iterate over array1, testing the elements one at a time with .includes() to produce the list of missing elements, then do the reverse to get the list of new elements.

You could use .filter() and arrow functions to keep it short:

var array1= ['11', '13', '14', '18', '22', '23', '25'];
var array2= ['11', '13', '15', '16', '17', '23', '25', '31'];

var missing_elements = array1.filter(v => !array2.includes(v));
var new_elements = array2.filter(v => !array1.includes(v));

console.log(missing_elements);
console.log(new_elements);
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Works well. But if array2 have duplicate values, then how to delete the duplicated value? Eg: var array2= ['11', '13', '15', '16', '17', '23', '25', '31','17','11']; – Divya Sep 11 '17 at 04:30
  • Removing duplicates from arrays is covered in other questions, including one with [this excellent answer](https://stackoverflow.com/a/9229821/615754). You could combine one of those techniques with what I've shown, or do a separate `.filter()` before or afterwards. – nnnnnn Sep 11 '17 at 04:33