Vianne
Vianne

Reputation: 578

Swap columns in a one-dimensional array in Javascript

I'm trying to swap 2 columns from a delimited text, but the farthest I got is grabbing the first column. This is what I'm trying to achieve.

// Input
A1—B1—C1
A2—B2—C2
A3—B3—C3

Swap column #1 with column #3. Delimiter is "—".

// Result
C1—B1—A1
C2—B2—A2
C3—B3—A3

JSFiddle

  var text = $('#input').val().split("\n");

  var delimiter = "—";
  var col_1 = $('#col_1').val() - 1;
  var col_2 = $('#col_2').val() - 1;

  var out = [];
  var col_arr = [];
  var col = '';

  // Get first column
  for (var i = 0; i < text.length; i++) {
    col_arr = text[i].split(delimiter);
    col = col_arr[col_1];
    if (col != undefined) col = col;
    else col = '';
    out[i] = col;
  }

  text = out.join('\n');

Upvotes: 0

Views: 186

Answers (3)

Ori Drori
Ori Drori

Reputation: 191986

It's a simple swap with a temp variable. I've used Array.map() to iterate the text array, but you can replace it with a `for...loop.

$("button").click(function() {
  var delimiter = "—";
  var rowDelimiter = "\n";
  var text = $('#input').val()
    .trim() // remove white space before and after the text
    .split(rowDelimiter);
  
  var col_1 = $('#col_1').val() - 1;
  var col_2 = $('#col_2').val() - 1;
  
  // check the cols to be a number between 0 and the amount of columns
  // and notify user if their not

  var result = text.map(function(row) {
    var arr = row.split(delimiter);
    
    var temp = arr[col_1]; // cache the value of col_1
    arr[col_1] = arr[col_2]; // set the value of col_2 1 to be that of column 2
    arr[col_2] = temp; // set the value of col_2 to be the value of temp
    
    return arr.join(delimiter);
  }).join(rowDelimiter);

  $('#output').val(result);
});
textarea {
  width: 100%;
  height: 120px
}

button {
  margin: 10px 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Swap col #<input id="col_1" value="2"> with col #<input id="col_2" value="3">

<br>

<textarea id="input">
A1—B1—C1—D1
A2—B2—C2—D2
A3—B3—C3—D3
</textarea>

<button>Swap</button>

<textarea id="output">

</textarea>

Upvotes: 1

Tom
Tom

Reputation: 2944

You've successfully split the text into an array of its constituent parts using split, you can now use the reverse Array function to reverse the order, and then rejoin all the parts together using the join Array function and your delimiter.

This simplifies your code in your for loop to this:

for (var i = 0; i < text.length; i++) {
  out[i] = text[i].split(delimiter).reverse().join(delimiter);
}

Upvotes: 3

aznoqmous
aznoqmous

Reputation: 121

split() returns an array, so what you can do is first processing your text data to an actual array so its easier to work on it :

function getArrayFromInput(){
  var arr = [];
  var lines = $('#input').val().split("\n");
  for (let line of lines){
    let column = line.split('—');
    arr.push(column);
  }
  return arr;
}
//returns [['A1','B1','C1'],['A2','B2','C2'],['A3','B3','C3']]

It'll be easier to do what you're trying to do then :)

function swapColumns(inputArr, col1, col2){
    var arr = JSON.parse(JSON.stringify(inputArr)); //get inputArr structure
    for(let i = 0; i<arr.length; i++){
        //swap the values
        arr[i][col1] = inputArr[i][col2];
        arr[i][col2] = inputArr[i][col1];
    }
    return arr;
}
//return your array with swaped columns

I'll then let you handle the array to text conversion !

Feel free to ask any question

Upvotes: 1

Related Questions