JeffVader JeffVader - 2 months ago 8
jQuery Question

Jquery - code being used

I have this code in a script.
I know what the result is, but not what it's actually doing.

var str = ',' + id + ',' + name;

names = names.map(function(value) {
if( value.indexOf(id) > -1 ) {
return (value.indexOf('add') === 0 ? 'add' : 'edit') + str;
}
return value;
});

if ( ($.inArray('edit' + str, names) == -1 && $.inArray('add' + str, names) == -1) ) {
names.push('edit' + str)
}


The person who gave me the script isn't available for comments.

it seems to be is
str
isn't in the array add it, if it is update it.

Can anyone give a brief overview of what it actually does.

Thanks

Answer

Looks like it's looking for specifically 'edit'+str and 'add'+str in the names array. If both are not present, then add 'edit'+str to the names array.

var str = ',' + id + ',' + name;

names = names.map(function(value) {
if( value.indexOf(id) > -1 ) { //if id is in value
    return (value.indexOf('add') === 0 ? 'add' : 'edit') + str; //if value starts with 'add' then return 'add'+str, otherwise return 'edit'+str
}
return value; //if id not in value, return value
});

if ( ($.inArray('edit' + str, names) == -1  && $.inArray('add' + str, names) == -1)   ) { //If 'edit'+str is not in the names array AND 'add'+str is not in the names array
    names.push('edit' + str) //add 'edit'+str to the names array
}