1d array to 2d array javascript code example

Example 1: CSV to 2D array javaescript

function csvToArray(csv, delimiter = ",", omitFirstRow = false) {
  console.log(csv.indexOf('\n'));
  return csv.slice(omitFirstRow ? csv.indexOf('\n')+1 : 0)
            .split("\n")
            .map((element) => element.split(delimiter));
}

let csv1 = "a,b\nc,d";
let csv2 = "a;b\nc;d";
let csv3 = "head1,head2\na,b\nc,d";

let result1 = csvToArray(csv1);
let result2 = csvToArray(csv2);
let result3 = csvToArray(csv3);

console.log(result1);
console.log(result2);
console.log(result3);

Example 2: javascript create 2d array

function create2DArray(rows, columns, value = (x, y) => 0) {
  var array = new Array(rows);
  for (var i = 0; i < rows; i++) {
    array[i] = new Array(columns);
    for (var j = 0; j < columns; j++) {
      array[i][j] = value(i, j);
    }
  }

  return array;
}

var array = create2DArray(2, 3, (row, column) => row + column);
console.log(array);
//output: [[0, 1, 2],
//         [1, 2, 3]]

Tags:

Java Example