从单独的值中在另一个(主)数组中创建一个数组

时间:2019-03-23 15:00:06

标签: javascript arrays multidimensional-array

问题

我有一串用逗号分隔的数值,我想将它们包括在数组中,并且每对都嵌套在主数组内作为我的图形顶点。

我该如何解决这个问题?

输入:

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

我希望他们成为:

输出:

var V_array = [[24,13],[47,20],[33,9],[68,18],[99,14],[150,33],[33,33],[34,15],[91,10]];

8 个答案:

答案 0 :(得分:8)

您可以Split on every second comma in javascript并通过将值转换为数字来映射拆分对。

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

答案 1 :(得分:2)

您可以使用函数reduce来对拆分字符串进行操作,并检查每个索引的mod。

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

答案 2 :(得分:2)

您可以将字符串拆分为数组,然后使用reduce方法。看看下面的代码

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)

答案 3 :(得分:2)

您可以使用execJSON.parse

var elements = document.getElementsByClassName('.className');
for(var i = 0; i < elements.length; i++){
    // Same like above...
}

答案 4 :(得分:1)

@GetMapping("/pdf/{Id}") @Secured({"ROLE_ADMIN", "ROLE_OPERATOR", "ROLE_GUEST"}) public ResponseEntity<PDDocument> findOnePdfByIdJob(@PathVariable("Id") Long id) throws DocumentException, IOException { Job job = jobService.findById(id); if (job == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } ObjectMapper objectMapper = new ObjectMapper(); String jsonInString = objectMapper.writeValueAsString(job); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(jsonInString); String prettyJsonString = gson.toJson(je); PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); contentStream.setFont(PDType1Font.COURIER, 12); contentStream.beginText(); contentStream.showText(jsonInString); contentStream.endText(); contentStream.close(); document.save("pdfBoxHelloWorld.pdf"); document.close(); HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity.ok() .headers(headers) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(document); } 上分割并使用,将线对分组为新的二维数组:

Array.reduce

如果索引为奇数,则可以使用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);进行相同操作,请跳过该元素并过滤掉Array.map元素:

undefined

答案 5 :(得分:1)

我的两分钱:) [新版本]

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

答案 6 :(得分:0)

这是我的解决方法。

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

答案 7 :(得分:0)

我的两分钱:)

(感谢 Code Maniac 使用JSON.parse的想法)

{{1}}