Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an arrays inside of another (main) array out of separated values

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]];
like image 221
Ahmad Murad Avatar asked Dec 08 '22 12:12

Ahmad Murad


2 Answers

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);
like image 81
Nina Scholz Avatar answered Dec 11 '22 10:12

Nina Scholz


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; }
like image 21
Ele Avatar answered Dec 11 '22 10:12

Ele