I've list of users:
const users = [
{
id: 1,
name: "Leanne Graham",
phone: "1-770-736-8031 x56442",
},
{
id: 2,
name: "Ervin Howell",
phone: "010-692-6593 x09125",
},
{
id: 3,
name: "Leanne Graham",
phone: "1-463-123-4447",
},
{
id: 4,
name: "Leanne Graham",
phone: "493-170-9623 x156",
},
{
id: 5,
name: "Chelsey Dietrich",
phone: "(254)954-1289",
},
{
id: 6,
name: "Mrs. Dennis Schulist",
phone: "1-477-935-8478 x6430",
},
{
id: 7,
name: "Kurtis Weissnat",
phone: "210.067.6132",
},
{
id: 8,
name: "Nicholas Runolfsdottir V",
phone: "586.493.6943 x140",
},
{
id: 9,
name: "Glenna Reichert",
phone: "(775)976-6794 x41206",
},
{
id: 10,
name: "Leanne Graham",
phone: "024-648-3804",
},
];
for (const user of users) {
let countUserOccured = users.reduce(
(acc, curr) => (acc += curr.name == user.name),
0
);
if (countUserOccured - 1 != 0) {
user.name += countUserOccured;
}
console.log(user);
}
And I want users name be unique.
if the name e.g. "Leanne Graham" in that case repeated many times I want first one add to his name 1, second one his name 2...
I've tried this approach: but its order DESC(from greater number of occurrence to the lowest I want it in order ASCending.
for (const user of users) {
let countUserOccured = users.reduce(
(acc, curr) => (acc += curr.name == user.name),
0
);
if (countUserOccured - 1 != 0) {
user.name += countUserOccured;
}
console.log(user);
}
you can do that with objects and counting the value that you want.
const counts = {};
users.forEach((user) => {
counts[user.name] = (counts[user.name] || 0) + 1;
});
console.log(counts)