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: array 2d to 1d
int array[width * height];
int SetElement(int row, int col, int value)
{
array[width * row + col] = value;
}
Example 3: numpy convert 1d array to 2d
import numpy as np
# 1D array
one_dim_arr = np.array([1, 2, 3, 4, 5, 6])
# to convert to 2D array
# we can use the np.ndarray.reshape(shape) function
# here shape is given by two integers seperated by a comma
# the two integers specify m,n for the new matrix
# ensure that the matrix that you are trying to generate
# has a size that meets the number of elements in the 1D array.
# for that make sure that
# m * n = number of elements in the one dimentional array
two_dim_arr = one_dim_arr.reshape(1, 6)
#which returns a 2D array
print(two_dim_arr)
# confirmed by the array.ndim attribute
print(two_dim_arr.ndim)
# you can even specify one of the dimensions as unknown by passing -1
# numpy will infer the length using the array and remaining dimensions
two_dim_arr = one_dim_arr.reshape(1,-1)
Example 4: numpy convert 1d array to 2d
import numpy as np
# 1D array
one_dim_arr = np.array([1, 2, 3, 4, 5, 6])
# To convert to 2D array
# we can use the np.newaxis to increase the dimesions in a array
# Using np.newaxis will increase the dimensions of your array by one dimension when used once.
two_dim_arr = one_dim_arr[np.newaxis, :]
print(two_dim_arr)
# inserting a axis at the first index creates a row vector
print()
# for column vector, insert axis at the second index
two_dim_arr = one_dim_arr[:,np.newaxis]
print(two_dim_arr)
print()
# we can also expand an array by inserting a new axis at a specified position with np.expand_dims.
two_dim_arr = np.expand_dims(one_dim_arr,axis = 0)
print(two_dim_arr)
print()
two_dim_arr = np.expand_dims(one_dim_arr,axis = 1)
print(two_dim_arr)
Example 5: convert json to 2d array
function jsonArrayTo2D(arrayOfObjects){
let header = [],
AoA = [];
arrayOfObjects.forEach(obj => {
Object.keys(obj).forEach(key => header.includes(key) || header.push(key))
let thisRow = new Array(header.length);
header.forEach((col, i) => thisRow[i] = obj[col] || '')
AoA.push(thisRow);
})
AoA.unshift(header);
return AoA;
}