Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!