

- 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
Commons 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' ]
- Related Questions & Answers
- Finding array intersection and including repeating elements in JavaScript
- Sorting an array including the elements present in the subarrays in JavaScript
- Difference of two lists including duplicates in Python
- Merge and remove duplicates in JavaScript Array
- How do I make an array with unique elements (remove duplicates) - JavaScript?
- Remove array duplicates by property - JavaScript
- Remove duplicates and map an array in JavaScript
- Efficient algorithm for grouping elements and counting duplicates in JavaScript
- Remove duplicates from array with URL values in JavaScript
- Counting duplicates and aggregating array of objects in JavaScript
- Remove duplicates from a array of objects JavaScript
- Add two array keeping duplicates only once - JavaScript
- Removing duplicates from a sorted array of literals in JavaScript
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Removing consecutive duplicates from strings in an array using JavaScript
Advertisements