Search code examples
javascriptjqueryarraysecmascript-5

Javascript : Increment name if exist


I want to push a name in an array, the name will be a default name.
If the name is already existing I need to add an integer to it before pushing, something like incrementing if instance is existing.

If not existing it should create an instance, Will do the same thing in the whole process but it should incrementing.

var arr = ['team banana', 'team melon', 'team melon 2', 'team orange'] 
var name = 'team apple'; // this is default team name
var xarr = [];

if(arr.length){
    // store the all instances of 'team apple'
    for(var c = 0; c <= arr.length; c++){
        if(arr[c] !== undefined){
            if(arr[c].indexOf('team apple')  > -1){
                xarr.push(arr[c].replace(/['0-9']/g,''))
            }
        }
    }
    // start the iterration
    for (var k=0; k<=arr.length; k++){
        // if existing
        if(arr[k] !== undefined){
            if(name === arr[k]) {
                arr.push(name+' ' + ( xarr.length))
            }else{
                // if not existing creat an instance of 'team apple'
                // arr.push(name) <--- this cause the browser to crash
            }
        }
    }
    xarr = []
}else{
    arr.push(name )
}

console.log(arr)

What i am expecting as a result is something like this:

['team banana', 'team melon', 'team melon 2', 'team orange','team apple','team apple 1', 'team apple 2' ...]

The block of code is already working except that if there is no instance of 'team apple' in the array, it started to crash

If the array looks like this, everything works well:

['team banana', 'team melon', 'team melon 2', 'team orange','team apple']

But if it looks like this:

['team banana', 'team melon', 'team melon 2', 'team orange']

It browser starting to crash.

This is the part of the code that causes it, i have no idea.

if(name === arr[k]) {
    arr.push(name+' ' + (xarr.length))
}else{
    // if not existing creat an instance of 'team apple'
    // arr.push(name) <--- this cause the browser to crash
}

I am not even sure if this is the right implementation fo this, were i really wanted is an incrementing name. any suggestion will be huge help. also i am limited only to ES5.

Thanks in advance


Solution

  • It's much easier just using filter and taking the resulting length as postfix. There are many loops in your code, and none but one would be needed

    const arr = ['team banana', 'team melon', 'team melon 2', 'team orange']
    const name = 'team apple';
    
    function addToArr(arr, name) {
      const postfix = arr.filter(e => e.replace(/\s\d+$/, '') === name).length || '';
      arr.push(`${name} ${postfix}`.trim());
      return arr;
    }
    
    console.log(addToArr(arr, name));
    console.log(addToArr(arr, name));
    console.log(addToArr(arr, name));

    ES 5 Version

    var arr = ['team banana', 'team melon', 'team melon 2', 'team orange']
    var name = 'team apple';
    
    function addToArr(arr, name) {
      var postfix = arr.filter(function(e) { return e.replace(/\s\d+$/, '') === name}).length || '';
      arr.push((name + ' ' + postfix).trim());
      return arr;
    }
    
    console.log(addToArr(arr, name));
    console.log(addToArr(arr, name));
    console.log(addToArr(arr, name));