
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding the common streak in two arrays in JavaScript
We are required to write a JavaScript function that takes in two arrays of literals, let’s call them arr1 and arr2.
The function should find the longest common streak of literals in the arrays. The function should finally return an array of those literals.
For example −
If the input arrays are −
const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['k', 'j', 'b', 'c', 'd', 'w'];
Then the output array should be −
const output = ['b', 'c', 'd'];
Example
Following is the code −
const arr1 = ['a', 'b', 'c', 'd', 'e']; const arr2 = ['k', 'j', 'b', 'c', 'd', 'w']; const longestCommonSubsequence = (arr1 = [], arr2 = []) => { let str1 = arr1.join(''); let str2 = arr2.join(''); const arr = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null)); for (let j = 0; j <= str1.length; j += 1) { arr[0][j] = 0; } for (let i = 0; i <= str2.length; i += 1) { arr[i][0] = 0; } for (let i = 1; i <= str2.length; i += 1) { for (let j = 1; j <= str1.length; j += 1) { if (str1[j - 1] === str2[i - 1]) { arr[i][j] = arr[i - 1][j - 1] + 1; } else { arr[i][j] = Math.max( arr[i - 1][j], arr[i][j - 1], ); } } } if (!arr[str2.length][str1.length]) { return ['']; } const res = []; let j = str1.length; let i = str2.length; while (j > 0 || i > 0) { if (str1[j - 1] === str2[i - 1]) { res.unshift(str1[j - 1]); j -= 1; i -= 1; } else if (arr[i][j] === arr[i][j - 1]) { j -= 1; } else { i -= 1; } } return res; }; console.log(longestCommonSubsequence(arr1, arr2));
Output
Following is the output on console −
['b', 'c', 'd']
- Related Questions & Answers
- Finding the continuity of two arrays in JavaScript
- Finding the difference between two arrays - JavaScript
- Finding Common Item Between Arbitrary Number of Arrays in JavaScript
- Finding deviations in two Number arrays in JavaScript
- Finding the sum of all common elements within arrays using JavaScript
- Finding maximum number from two arrays in JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding the missing number between two arrays of literals in JavaScript
- JavaScript Program for find common elements in two sorted arrays
- Finding the inclination of arrays in JavaScript
- How to find the common elements between two or more arrays in JavaScript?
- Return the common filling value of two masked arrays in Numpy
- Finding maximum length of common subarray in JavaScript
- Finding two numbers given their sum and Highest Common Factor using JavaScript
- Taking common elements from many arrays in JavaScript
Advertisements