Add number to comma separated list

The list is as follows:

3434,346,1,6,46

How can I add a number to it using javascript, but only if it does not already exist in it?

+7
source share
3 answers

Assuming your initial value is a string (you didn't say).

 var listOfNumbers = '3434,346,1,6,46', add = 34332; var numbers = listOfNumbers.split(','); if(numbers.indexOf(add)!=-1) { numbers.push(add); } listOfNumbers = numbers.join(','); 

I basically convert a string to an array, check for the existence of a value using indexOf (), adding only if it does not exist.

Then I convert the value back to string using join.

+13
source

If this is a string, you can use the functions .split() and .join() , as well as .push() :

 var data = '3434,346,1,6,46'; var arr = data.split(','); var add = newInt; arr.push(newInt); data = arr.join(','); 

If it is already an array, you can simply use .push() :

 var data = [3434,346,1,6,46]; var add = newInt; data.push(add); 

UPDATE: did not read the last line to check for duplicates, the best approach I can think of is a loop:

 var data = [3434,346,1,6,46]; var add = newInt; var exists = false; for (var i = 0; i < input.length; i++) { if (data[i] == add) { exists = true; break; } } if (!exists) { data.push(add); // then you would join if you wanted a string } 
+2
source

You can also use regex:

 function appendConditional(s, n) { var re = new RegExp('(^|\\b)' + n + '(\\b|$)'); if (!re.test(s)) { return s + (s.length? ',' : '') + n; } return s; } var nums = '3434,346,1,6,46' alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12' alert( appendConditional(nums, '6') ); // '3434,346,1,6,46' 

Oh, since some really look like ternary operators and obfustically short code:

 function appendConditional(s, n) { var re = new RegExp('(^|\\b)' + n + '(\\b|$)'); return s + (re.test(s)? '' : (''+s? ',':'') + n ); } 

No jQuery, padding, or cross-browser issues. :-)

+2
source

All Articles