admin管理员组

文章数量:1429841

Problem

I have a string of numerical values separated by mas, 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]];

Problem

I have a string of numerical values separated by mas, 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]];
Share Improve this question edited Mar 23, 2019 at 16:30 Emma 27.8k12 gold badges48 silver badges71 bronze badges asked Mar 23, 2019 at 15:00 Ahmad MuradAhmad Murad 435 bronze badges 2
  • 1 Hi! Please take the tour (you get a badge!) and read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search 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 minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Commented Mar 23, 2019 at 15:05
  • 2 Split the string at , and then Split array into chunks – adiga Commented Mar 23, 2019 at 15:07
Add a ment  | 

8 Answers 8

Reset to default 7

You could Split on every second ma 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);

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; }

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)

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)  )

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)

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);

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 )

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);

本文标签: javascriptCreate an arrays inside of another (main) array out of separated valuesStack Overflow