 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Common element with least index sum in JavaScript
Problem
We are required to write a JavaScript function that takes in two arrays of literals, arr1 and arr2, as the first and the second argument.
Our function should find out the common element in arr1 and arr2 with the least list index sum. If there is a choice tie between answers, we should output all of them with no order requirement.
For example, if the input to the function is−
const arr1 = ['a', 'b', 'c', 'd']; const arr2 = ['d', 'a', 'c'];
Then the output should be −
const output = ['a'];
Output Explanation
Since 'd' and 'a' are common in both the arrays the index sum of 'd' is 3 + 0 = 3 and that of 'a' is 0 + 1 = 1, hence 'a' is the required element.
Example
Following is the code −
const arr1 = ['a', 'b', 'c', 'd']; const arr2 = ['d', 'a', 'c']; const findCommon = (arr1 = [], arr2 = []) => {    let sum = Infinity    const map = arr1.reduce((acc, str, index) => {       acc[str] = index       return acc    }, {})    for (let i = 0; i < arr2.length; i++) {       const index1 = map[arr2[i]]       if (index1 >= 0 && index1 + i < sum) {          sum = index1 + i       }    }    const result = []    for (let i = 0; i < arr2.length; i++) {       const index1 = map[arr2[i]]       if (index1 >= 0 && index1 + i === sum) {          result.push(arr2[i])       }    }    return result } console.log(findCommon(arr1, arr2));  Output
Following is the console output−
['a']
Advertisements
 