How to get the difference between two arrays in JavaScript?
To get the difference between two arrays in JavaScript, try to run the following code. Here, we’re using some method like split(), indexOf(), sort(), etc to get the elements, which aren’t the same in both the arrays &mnus;
Example
<html>
<head>
<title>JavaScript Dates</title>
</head>
<body>
<script>
function arrDifference (arr1, arr2) {
var arr = [];
arr1 = arr1.toString().split(',').map(Number);
arr2 = arr2.toString().split(',').map(Number);
// for array1
for (var i in arr1) {
if(arr2.indexOf(arr1[i]) === -1)
arr.push(arr1[i]);
}
// for array2
for(i in arr2) {
if(arr1.indexOf(arr2[i]) === -1)
arr.push(arr2[i]);
}
return arr.sort((x,y) => x-y);
}
document.write(arrDifference([50, 40, 90], [70, 50, 99, 40, 90]));
</script>
</body>
</html>
Output
70,99
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP