Home > Back-end >  Compare string from array and if duplicate string available then append Incremented number to the du
Compare string from array and if duplicate string available then append Incremented number to the du

Time:02-22

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.

CodePudding user response:

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, '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}-${(finalIndex   1)}` : `${requestBody.name}-1`, age: requestBody.age });
} else {
  listOfValues.push(requestBody);
}
console.log(listOfValues);

CodePudding user response:

You can do it by following technique:

let listOfValues = [
{
  name: "Peter",
  age: 25
},
{
  name: "Paul",
  age: 35
},
{
  name: "Paul-1",
  age: 35
},

{
  name: "Dom",
  age: 28
}]

let list=[]
listOfValues.forEach((item,index)=>{
  let a=list.filter((e)=>e.name===item.name);
  if(a.length>0){
    list.push({name:`${item.name}-${a.length 1}`,age:item.age});
  }
  else {
    list.push(item);
  }
});

Now list will contain your final list of values

  • Related