Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Inserting empty string in place of repeating values in JavaScript
We have to write a function that takes in an array, removes all duplicates from it and inserts the same number of empty strings at the end.
For example: If we find 4 duplicate values we have to remove them all and insert four empty strings at the end.
Therefore, let's write the code for this function ?
Example
The code for this will be ?
const arr = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];
const deleteAndInsert = arr => {
const creds = arr.reduce((acc, val, ind, array) => {
let { count, res } = acc;
if(array.lastIndexOf(val) === ind){
res.push(val);
}else{
count++;
};
return {res, count};
}, {
count: 0,
res: []
});
const { res, count } = creds;
return res.concat(" ".repeat(count).split(" "));
};
console.log(deleteAndInsert(arr));
Output
The output in the console will be ?
[
2, 3, 5, 12, 23, 4, 1,
'', '', '', '', '', '', '',
'', '', '', ''
]
How It Works
The function uses reduce() to iterate through the array. For each element, it checks if the current index matches the last occurrence index using lastIndexOf(). If they match, it's the final occurrence and gets added to the result. Otherwise, it's a duplicate and the count increases.
Finally, empty strings are generated using " ".repeat(count).split(" ") and concatenated to the unique values array.
Alternative Approach Using Set
const arr2 = [1,2,3,1,2,3,2,2,3,4,5,5,12,1,23,4,1];
const deleteAndInsertSimple = arr => {
const uniqueValues = [...new Set(arr)];
const duplicateCount = arr.length - uniqueValues.length;
return uniqueValues.concat(Array(duplicateCount).fill(''));
};
console.log(deleteAndInsertSimple(arr2));
[
1, 2, 3, 4, 5, 12, 23,
'', '', '', '', '', '', '',
'', '', '', ''
]
Conclusion
Both approaches effectively remove duplicates and replace them with empty strings. The Set approach is more straightforward, while the reduce method provides more control over the deduplication process.
