7

the list looks like:

3434,346,1,6,46

How can I append a number to it with javascript, but only if it doesn't already exist in it?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Alex
  • 66,732
  • 177
  • 439
  • 641

3 Answers3

14

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(',');

Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.

I then convert the value back to a string using join.

Yahel
  • 37,023
  • 22
  • 103
  • 153
simjay
  • 221
  • 2
  • 3
  • 2
    `Array.prototype.indexOf` isn't supported in older browsers, so you'd need a shim. Also, you should check `!=-1`, since it'll return a false negative if the number is in the first slot. – Yahel Aug 02 '11 at 01:16
  • as a side note, its ie8+ so you would be much better offwith an `Array.indexOf` http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array/143863#143863 – naveen Aug 02 '11 at 01:17
  • 2
    Given the tags indicate the poster is using jQuery, the jQuery equivalent of [`$.inArray(value, array)`](http://api.jquery.com/jQuery.inArray/) should be cross browser compatible, and directly replace `Array.indexOf()`. As with `indexOf()`, remember to check the result != -1. – GregL Aug 02 '11 at 01:32
2

If that is a string, you can use the .split() and .join() functions, 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 that is already an array, you can just use .push():

var data = [3434,346,1,6,46];
var add = newInt;

data.push(add);

UPDATE: Didn't 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
}
Ribose
  • 2,223
  • 16
  • 22
1

You can also use a regular expression:

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 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, "shims" or cross-browser issues. :-)

RobG
  • 142,382
  • 31
  • 172
  • 209