'Compare string from array and if duplicate string available then append Incremented number to the duplicate string when creating a record
I need to create a record but I have to check whether in the given list record with same name is available or not if available then append with incremented number. Below is the given list.
let listOfValues = [
{
name: "Peter",
age: 25
},
{
name: "Paul",
age: 35
},
{
name: "Paul-1",
age: 35
},
{
name: "Dom",
age: 28
}
]
And, I am creating a record as below:
let requestBody = {
name: "Paul",
age: 28
}
Now, I want to compare name from requestBody with the given list. Suppose, Paul is already available then it will check if Paul-1 is also available then it should increment with one number like Paul-2. Any help would be appreciated.
Solution 1:[1]
Generic Solution
- Generate a Regex to check a string that starts with the name in the
requestBody. - Filter down the list by searching for the names matching the Regex.
- You should split the names on
"-"and return the index from the name. - Sort the index list so that the largest index is at the end of the list.
- Check length of the list filtered out, if its zero, you can directly push.
- If its one you can push the element by appending 1 to the name.
- If its greater than one increment the last index and append it to name and push.
Working Fiddle
let listOfValues = [
{ name: "Peter", age: 25 },
{ name: "Paul", age: 35 },
{ name: "Paul-1", age: 35 },
{ name: "Dom", age: 28 }
];
let requestBody = {
name: "Paul",
age: 28
}
const regex = new RegExp('^' + requestBody.name.split('-')[0], 'i');
const existingList = listOfValues.filter((item) => item.name.match(regex)).map((item) => +item.name.split('-')[1]).sort((a, b) => a - b);
if (existingList.length > 0) {
const finalIndex = existingList[existingList.length - 1];
listOfValues.push({ name: finalIndex ? `${requestBody.name.split('-')[0]}-${(finalIndex + 1)}` : `${requestBody.name}-1`, age: requestBody.age });
} else {
listOfValues.push(requestBody);
}
console.log(listOfValues);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
