[Snippet] Generate a new unique "name" string from an existing list - The Koch Family
The Koch Family The Koch Family

Latest news

جاري التحميل ...

[Snippet] Generate a new unique "name" string from an existing list

Suppose that we have a list of employees. Everytime, we want to add new employee into this list, the name of the employee will be generated with the following rules:
- the name of the new one is set to "[originalname] 1"
- in case the name already exist, "[originalname] 2" is used, and so on.

Here is my code snippet by Javascript:
var employees =[
{id: 1, name: 'name'},
{id: 2, name: 'name 1'},
{id: 3, name: 'name 2'},
{id: 5, name: 'name 4'}
];

var commonUtils = {

isExistName: function(_name, _collection, _prop) {

for(var i = 0; i< _collection.length; i++){

if(_collection[i][_prop].localeCompare(_name)==0){

return true;
}

}

return false;
},

generateNewName: function(_name, _collection, _prop){
var i = 1;
var searching = true;
while (searching) {
var newName = _name+ " " + i;
if (!this.isExistName(newName, _collection, _prop)) {
return newName;
}
i++;
};
}

};

console.log("newName: " + commonUtils.generateNewName("name", employees, 'name'))

Can check here: https://jsfiddle.net/avebff8t/2/

Comments



If you like the content of our blog, we hope to stay in constant communication, just enter your email to subscribe to the blog's express mail to receive new blog updates, and you can send a message by clicking on the button next ...

إتصل بنا

About the site

author The Koch Family <<  Welcome! I'm so glad that you stopped by Your Modern Family blog. Together, we will talk about raising kids, organizing the home and saving money! and Tips & tricks and more…

< Learn more ←

Blog stats

Sparkline 2513183

All Copyrights Reserved

The Koch Family

2020