Vijayakumar S
Vijayakumar S

Reputation: 5

Generating series numbers with adding String at middle

Am writing JavaScript plugin to one of my client, in this i need to generate a series strings like "1,2,D,3,4" / "1,D,2,3,4,5,6". length can be n numbers. "D" positions are stored in a separate string like 2,4. Here, based upon this length we want to generate like below

String = 1,2,3,4,5 D Positions: 2,4 Final result should be: 1,D,2,D,3

Something i tried,

 var deletedString = "2,4"
    var Values = "1,2,3,4,5,6";
    var lengthFromValues = SplitString_ToArray(Values).length;
    var deletedArray = splitString_ToArray(deletedString);
    var temp_arr = [];
    for(var i = 1; i <= lengthFromValues; i++) {        
        if(deletedArray[i-1] > 0) {
          temp_arr.push("D");
        } else temp_arr.push(i);
    }
alert(temp_arr.toString());

Note: SplitString_ToArray function is a self written function which will convert(split) string to array.

Will someone help me?

Upvotes: 0

Views: 82

Answers (3)

Vijayakumar Selvaraj
Vijayakumar Selvaraj

Reputation: 523

var deletedString = "2,4"; /* Sort the values */
var Values = "1,2,3,4,5,6";

var allValues = Values.split(','),
    length = allValues.length;

deletedString.split(',').forEach(function(position) {
    allValues.splice(parseInt(position) - 1, 0, 'D');
});

var newValues = allValues.splice(0, length).join();
alert(newValues);

Upvotes: 0

Kwebble
Kwebble

Reputation: 2075

Using a forEach loop this should do it:

var deletedString = "2,4";
var Values = "1,2,3,4,5,6";

var toDelete = deletedString.split(','),
    allValues = Values.split(','),
    length = allValues.length;

toDelete.sort(function(a, b) {return a - b;});

toDelete.forEach(function(position) {
    allValues.splice(parseInt(position) - 1, 0, 'D');
});

var newValues = allValues.splice(0, length).join();
alert(newValues);

Upvotes: 0

the berserker
the berserker

Reputation: 1594

Check this I've changed a logic a bit. Actually you can use deletedString values to replace values in Values that you convert to array and then you just put the array back to string. jsFiddle

var deletedString = "2,4"
var Values = "1,2,3,4,5,6";
var deletedArray = SplitString_ToArray(deletedString);
var valuesArray = SplitString_ToArray(Values);
var finalLength = valuesArray.length;

for (i=0; i< deletedArray.length; i++){
    console.log(deletedArray[i]);
    var idxToReplace = parseInt(deletedArray[i]-1); // substract 1, because your indexes are 1-based
    valuesArray.splice(idxToReplace,0,'D');
}

// back to string
valuesArray = valuesArray.slice(0, finalLength);
var result = valuesArray.join();
alert(result);

function SplitString_ToArray(inString){
    var result = inString.split(',');
    console.log(result);
    return result;
}

Upvotes: 1

Related Questions