Convert a comma-separated string to a multidimensional array

Asked

Viewed 2,052 times

9

I have a string thus ...

var listAdd = "1789, 3, 8 , 1788, 3, 8, 1790, 3, 9"

How do I convert into a array as below?

[1789,3,8], [1788,3,8], [1790,3,9]

The code I’m trying isn’t working:

var ArrayAdd = new Array();

for (i = 0; i < listAdd.length; i++) {
                s = "";
                s = String(listAdd[i]);
                ArrayAdd.push(s);
            }

3 answers

8


There’s a lot of mistakes in there, and I can’t even begin to say what. There are some ways to solve this, I preferred so, although maybe not the most efficient (but in general the staff usually propose, and I know they will post here even worse at this point), but I would need to test because without using the split() can give a gain on one side and loss on the other.

You need to break the text into parts according to the comma. Then group 3 by 3 by mounting a new array with each new group, if you can understand.

I did by inferring criteria by the expected answer that was posted, there is no such thing as "no more criteria", if they became ambiguous may not give the real result that should give because the AP may have been mistaken in something putting the problem. Simple and performatic:

let texto = "1789, 3, 8 , 1788, 3, 8, 1790, 3, 9";
let array = new Array();
let quebrado = texto.split(",");
for (let i = 0; i < quebrado.length; i+= 3) array.push([parseInt(quebrado[i]), parseInt(quebrado[i + 1]), parseInt(quebrado[i + 2])]);
console.log(array);

I put in the Github for future reference.

7

One way to accomplish the necessary transformation is to follow the following steps:

  • Use the function split to separate the results by ,;
  • Perform the function map in the array resulting to remove spaces with trim and convert each item to integer with parseInt;
  • Using the proposed function in the answer to the question Split array into smaller groups to divide the array previously obtained.

const separar = (itens, maximo) => {
  return itens.reduce((acumulador, item, indice) => {
    const grupo = Math.floor(indice / maximo);
    acumulador[grupo] = [...(acumulador[grupo] || []), item];
    return acumulador;
  }, []);
};

const lista = '1789, 3, 8 , 1788, 3, 8, 1790, 3, 9';
const resultados = lista.split(',').map((item) => parseInt(item.trim(), 10));
console.log(separar(resultados, 3));


String.prototype.split()

The method split() divides an object String in a array of strings by separating the string in substrings.


Array.prototype.map()

The map() method invokes the callback function passed by argument to each Array element and returns a new Array as a result.

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots é [1, 2, 3], numbers ainda é [1, 4, 9]

String.prototype.Trim()

The method trim() removes whitespaces (whitespaces) from the beginning and/or end of a text. It is considered white space (space, tab, fixed/hard space, etc.) and every end-of-line sign of text (LF, CR, etc..).


parseint()

The function parseInt() analyzes an argument string and returns an integer in base specified.

6

Every three commas it replaces with #, then separate by # and , converting to Number

const str = '1789, 3, 8 , 1788, 3, 8, 1790, 3, 9';

let index = 0;

const result = str
    .replace(/[,]/g, _ => ++index % 3 === 0 ? '#' : ',')
    .split('#')
    .map(e => e.split(',').map(n => Number(n)));

console.log(result);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.