
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
Including Duplicates in Array Elements in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of strings, arr, as the first and the only argument.
Our function is supposed to return an array of all characters that show up in all strings within the array arr (including duplicates).
For example, if a character occurs 2 times in all strings but not 3 times, we need to include that character 2 times in the final answer.
For example, if the input to the function is −
const arr = ['door', 'floor', 'crook'];
Then the output should be −
const output = ['r', 'o', 'o'];
Example
The code for this will be −
const arr = ['door', 'floor', 'crook']; const findCommon = (arr = []) => { let prev = null; arr.forEach((str) => { const next = {}; for(const val of str){ if(!prev){ next[val] = (next[val] || 0) + 1; }else if(prev[val]){ prev[val] -= 1; next[val] = (next[val] || 0) + 1; }; }; prev = next; }); const res = Object.keys(prev).reduce((acc, val) => { for(let i = 0; i < prev[val]; i++){ acc.push(val); } return acc }, []); return res; }; console.log(findCommon(arr));
Output
And the output in the console will be −
[ 'r', 'o', 'o' ]
Advertisements