Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append number to a comma separated list

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?

like image 674
Alex Avatar asked Aug 02 '11 01:08

Alex


People also ask

How do I concatenate comma separated values in SQL?

Concatenate Rows Using COALESCE All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do you turn a column of data into a comma separated list?

Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)

How do I convert Excel data to comma separated text?

You can convert an Excel worksheet to a text file by using the Save As command. Go to File > Save As. Click Browse. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).


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

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.

like image 184
simjay Avatar answered Oct 06 '22 23:10

simjay


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
}
like image 36
Ribose Avatar answered Oct 07 '22 01:10

Ribose