4

Problem

I have a string of numerical values separated by commas, and I want to include them in an array, and also each pair of them to be an array nested inside of the main array to be my drawing vertices.

How do I solve this problem?

Input:

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

what I want them to be is:

Output:

var V_array = [[24,13],[47,20],[33,9],[68,18],[99,14],[150,33],[33,33],[34,15],[91,10]];
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    Hi! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Mar 23 '19 at 15:05
  • 2
    Split the string at `,` and then [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) – adiga Mar 23 '19 at 15:07

8 Answers8

7

You could Split on every second comma in javascript and map the splitted pairs by converting the values to number.

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10",
    result = vertices.match(/[^,]+,[^,]+/g).map(s => s.split(',').map(Number));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can use the function reduce which operates over the splitted-string and check for the mod of each index.

let str = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

let result = str.split(',').reduce((a, s, i) => {
  a.curr.push(Number(s));
  if ((i + 1) % 2 === 0) {
    a.arr.push(a.curr);
    a.curr = [];
  }
  
  return a;
}, {arr: [], curr: []}).arr;

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Ele
  • 33,468
  • 7
  • 37
  • 75
2

You can split string into array and use reduce method. Take a look at the code below

const vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

const numbers = vertices.split(',').map(Number)

const res = numbers
  .reduce((acc, number, index, srcArray) => {
    if (index % 2) {
      return acc
    }

    return [
      ...acc,
      [ number, srcArray[index + 1] ],
    ]
  }, [])

console.log(res)
lankovova
  • 1,396
  • 8
  • 15
1

Split on the , and use Array.reduce to group the pair into a new 2-D array:

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";
const pair = vertices.split(",").reduce((acc, ele, idx, arr) => {
  if(idx === 0  || idx%2 === 0) {acc.push([+ele, +arr[idx + 1]]);}
  return acc;
}, []);
console.log(pair);

Same can be done using Array.map, if the index is odd skip the element and filter out the undefined elements:

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";
const pair = vertices.split(",").map((ele, idx, arr) => (idx === 0 || idx%2 === 0) ? [+ele, +arr[idx + 1]] : undefined).filter(e => e);
console.log(pair);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

You can use exec and JSON.parse

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

var array1;
var reg = /[^,]+,[^,]+/g
let op = []

while((array1 = reg.exec(vertices))!== null){
  op.push(JSON.parse(`[${array1[0]}]`))
}

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

My two cents :) [new version]

let
  str     = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10",
  pair    = [],
  triplet = [];

JSON.parse(`[${str}]`).forEach((e,i)=>{pair.push( (i%2)?[pair.pop(),e]:e)})

console.log ( 'pair:', JSON.stringify(pair) )


// bonus => same idea for triplet :

JSON.parse(`[${str}]`).forEach((e,i)=>{
  if      ( (i%3)===2 )  triplet.push( [triplet.shift(),triplet.pop(),e] )
  else if ( (i%3)===0 )  triplet.unshift(e)
  else                   triplet.push(e)
})

console.log ( 'triplet:', JSON.stringify(triplet)  )
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

Here is my solution.

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

vertices = vertices.split(",");

function convertToMultiArray (arr, length) {
  var nArr = [];
  while(arr.length > 0) {
   nArr.push(arr.splice(0,length));
  } 
  return nArr;
}

const res = convertToMultiArray(vertices, 2);

console.log('res', res);
Ulrich Dohou
  • 1,509
  • 14
  • 25
0

My two cents :)

( thanks to Code Maniac for the idea of using JSON.parse )

let str = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

let result = JSON.parse(`[${str}]`).reduce((acc, cur, i) => {
  if (i===1) return [[acc,cur]]

  if (i%2)  acc.push( [acc.pop(), cur] )
  else      acc.push( cur )

  return acc
});

console.log ( result )
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40