
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compare Two Arrays of Single Characters and Return the Difference in JavaScript
We are required to compare, and get the difference, between two arrays containing single character strings appearing multiple times in each array.
Example of two such arrays are −
const arr1 = ['A', 'C', 'A', 'D']; const arr2 = ['F', 'A', 'T', 'T'];
We will check each character at the same position and return only the parts who are different.
Example
const arr1 = ['A', 'C', 'A', 'D']; const arr2 = ['F', 'A', 'T', 'T']; const findDifference = (arr1, arr2) => { const min = Math.min(arr1.length, arr2.length); let i = 0; const res = []; while (i < min) { if (arr1[i] !== arr2[i]) { res.push(arr1[i], arr2[i]); }; ++i; }; return res.concat(arr1.slice(min), arr2.slice(min)); }; console.log(findDifference(arr1, arr2));
Output
And the output in the console will be −
[ 'A', 'F', 'C', 'A', 'A', 'T', 'D', 'T' ]
Advertisements