6

I have a string with space-separated unique numbers as following:

"2 4 13 14 28 33"

Need a quick and efficient way to switch a pair of them in form:

switchNumbers(2, 28)
// result: "28 4 13 14 2 33"

I could split the string and search for values, but that sounds boring. Any better idea?

Tushar
  • 85,780
  • 21
  • 159
  • 179
skobaljic
  • 9,379
  • 1
  • 25
  • 51
  • 3
    What have you tried yourself so far to solve the problem? Have you done any research? Do you have a problem in your current code? – Anonymous Jun 19 '15 at 15:09
  • 4
    I am boring, what's wrong with boring! – Alex K. Jun 19 '15 at 15:10
  • 2
    "but that sounds boring" - you might want to clarify how you judge excitement so we know where to pitch the answers... Or more seriously that method is the one I'd go for, it would work and for the example you've given wouldn't even suck that much. What about that method do you not like (I'm assuming "boring" was just facetious). – Chris Jun 19 '15 at 15:11
  • You could use regex instead... – brso05 Jun 19 '15 at 15:11
  • 1
    Will all numbers be unique or could numbers be repeated? – brso05 Jun 19 '15 at 15:11
  • I do not want to split string, than loop over element. I am also not sure how would I use regex, probably would wrap string with spaces then search... everything I think of does not sound exciting, just boring. – skobaljic Jun 19 '15 at 15:12
  • possible duplicate of [array.contains(obj) in JavaScript](http://stackoverflow.com/q/237104/3150271) – Anonymous Jun 19 '15 at 15:24
  • @Anonymous NO! This is not the duplicate – Tushar Jun 19 '15 at 15:30
  • @Tushar Sure, it is. It is possibly closer to [Best way to find an item in a JavaScript array?](http://stackoverflow.com/q/143847/3150271), but that was marked as a duplicate of the other, so better to skip straight to the main question. Anyway, I didn't actually mark it as a duplicate. – Anonymous Jun 19 '15 at 15:31

7 Answers7

10

You can take advantage of array functions instead of strings.

See comments inline in the code:

var str = "2 4 13 14 28 33";

// Don't use `switch` as name
function switchNumbers(a, b) {
    var arr = str.split(' ');
    // Convert string to array

    // Get the index of both the elements
    var firstIndex = arr.indexOf(a.toString());
    var secondIndex = arr.indexOf(b.toString());


    // Change the position of both elements
    arr[firstIndex] = b;
    arr[secondIndex] = a;


    // Return swapped string
    return arr.join(' ');
}


alert(switchNumbers(2, 28));

DEMO

Tushar
  • 85,780
  • 21
  • 159
  • 179
8

Try also:

var numbers = "2 4 13 14 28 33";

function switchNum(from, to){
  return numbers.replace(/\d+/g, function(num){
    return num == from ? to : num == to ? from :  num
  })
}

alert(switchNum(2, 28)) //result: "28 4 13 14 2 33"

Note: Do not use switch as function name, switch is a statement for JavaScript.

5

I can't judge if this is boring or not but at least it's not splitting and looping :)

function switchNumbers(str, x, y) {
  var regexp = new RegExp('\\b(' + x + '|' + y + ')\\b', 'g'); // /\b(x|y)\b/g
  return str.replace(regexp, function(match) { return match == x ? y : x; });
}

var s = "2 4 13 14 28 33";

document.write('<pre>' + switchNumbers(s, 2, 28) + '</pre>');
Jason Cust
  • 10,743
  • 2
  • 33
  • 45
2

I'm sure this isn't the best way.. but it works..

var swapnums = function(x,first,second) {
    var y = x.split(" ");
    var locOfFirst = y.indexOf(first.toString());
    var locOfSecond = y.indexOf(second.toString());
    y[locOfFirst] = second.toString();
    y[locOfSecond] = first.toString();
    return y.join(" ");
};
skobaljic
  • 9,379
  • 1
  • 25
  • 51
Tim
  • 25
  • 1
  • 5
1

I think your best solution might be to use JavaScript's native replace method for strings.

W3Schools has a nice low-down on it here. It should do exactly what you want, but may replace ALL the numbers you specify, so be sure to say something like var replacement = str.replace("2 ", "28 ");

EDIT: Pointed out a good flaw with this. Instead you could try:

EDIT2: Opps, had some flaws in the original code. Tested and works fine! :)

    function replaceNumbers(x1, x2, str) {
        var strMod = " " + str + " "
        var x1Mod = " " + x1 + " "
        var x2Mod = " " + x2 + " "
        
        // Want to replace "farthest" first to ensure correct replacement.
        if (str.indexOf(x1Mod) > str.indexOf(x2Mod)) {
            strMod = strMod.replace(x1Mod, x2Mod)
            strMod = strMod.replace(x2Mod, x1Mod)
        } else {
            strMod = strMod.replace(x2Mod, x1Mod)
            strMod = strMod.replace(x1Mod, x2Mod)
        }
        
        return strMod.slice(1, strMod.length - 1)
    }

   var numbers = "2 4 13 14 28 33";
   alert(replaceNumbers(2, 33, numbers))
Rose R.
  • 141
  • 11
  • 1
    Guess would have to wrap the string first with space, than to use " 2 " and " 28 " (because 28 can be at end, than "2 " would also match from "12 "? – skobaljic Jun 19 '15 at 15:14
  • Just tested and fixed it! Forgot to do the other two replacements and forgot slice end is non-inclusive. I added a code snippet with your alert. :) – Rose R. Jun 19 '15 at 16:01
1

Something like that should work.

var str= "2 4 13 14 28 33";
function switchNumbers(a, b) {
    var arr = str.split(" ");
    var first= arr.indexOf(a), second = arr.indexOf(b);
    arr[first] = arr.splice(second, 1, arr[first])[0];
    return arr.join(" ");
}

Jsfiddle demo

Demonia
  • 332
  • 3
  • 14
1
var str = "2 4 13 14 28 33";
switchNumbers(2,28);  // call
function switchNumbers(a,b)
{


var split_ = str.split(" ");

var index_of_1 = split_.indexOf(a+"");
var index_of_2 =  split_.indexOf(b+"")

temp =  split_[index_of_1];
split_[index_of_1] = split_[index_of_2] ;
split_[index_of_2] = temp ;


split_.toString(" "); // Answer
}
Sachin Gadagi
  • 749
  • 5
  • 14