How to set the duplicate value is an array object to empty string.
const arr= [
{ name: 'someName1', age: 12 },
{ name: 'someName2', age: 13 },
{ name: 'someName3', age: 14 },
{ name: 'someName4', age: 15 },
{ name: 'someName4', age: 16 },
{ name: 'someName5', age: 15 },
{ name: 'someName3', age: 17 },
{ name: 'someName2', age: 18 },
];
expected result like below:
const resultArr = [
{ name: 'someName1', age: 12 },
{ name: 'someName2', age: 13 },
{ name: 'someName3', age: 14 },
{ name: 'someName4', age: 15 },
{ name: '', age: 16 },
{ name: 'someName5', age: 15 },
{ name: '', age: 17 },
{ name: '', age: 18 },
]
I have tried but not getting exact result,
arr.map((res, i=index) => {
const getNum = i === 0 ? i : i - 1;
const prev = arr[getNum].name;
if (res.name === prev) {
res.name = '';
}
3
Answers
Your function is incorrect. It only compares the current value with the previous one, and always clears the name at index 0.
A more effective approach would be to initialize an array of strings before the map function, and update this array whenever a new name is encountered. Then, simply check if the current name already exists in the array.
You could take a
Set
in a closure for seen names and map either the object or take a new object with emptyname
property.You can keep track of the names you’ve seen with a
Set
while you’remap
ping over the data to create the new data.