Home > Net >  Slice/convert 1D array to 2D array based on defined length in JavaScript
Slice/convert 1D array to 2D array based on defined length in JavaScript

Time:12-13

I have 1D pointer array like below:

Darray = [{x: 334, y: 400.5}, {x: 237, y: 389},{x: 149, y: 387.5},{x: 55, y: 379.5},{x: 210, y: 301.5},{x: 48, y: 295.5},{x: 378.5, y: 224.5},{x: 283, y: 217.5},{x: 121.5, y: 211.5},{x: 198.5, y: 211.5},{x: 42.5, y: 201},{x: 33, y: 134},{x: 364, y: 142},{x: 268.5, y: 137},{x: 192, y: 136.5},{x: 106, y: 131.5},{x: 263.5, y: 68},{x: 182.5, y: 63.5},{x: 102.5, y: 61.5},{x: 344.5, y: 65.5},{x: 32, y: 52}]
        //console.log(Darray)
        const points = Darray.slice();
        points.sort((a, b) => a.y - b.y);
        console.log(points)

I want to convert this 1D array into 2D array based on the array row length. For example,

row_length = [5, 5, 5, 2, 4]
new_Darray = [[element[1,1],element[1,2], element[1,3], element[1,4], element[1,5],
             [element[2,1],element[2,2], element[2,3], element[2,4], element[2,5],
             [element[3,1],element[3,2], element[3,3], element[3,4], element[3,5],
             [element[4,1],element[4,2],
             [element[5,1],element[5,2], element[5,3], element[5,4], element[5,5]]

Here, element[i] represents {x:someValue, y:someValue} Sorry, if I wrongly represented anything. Any help will be highly appreciated.

CodePudding user response:

Using map, slice and temp variable, can be simplified to one-liner

const Darray = [
  { x: 334, y: 400.5 },
  { x: 237, y: 389 },
  { x: 149, y: 387.5 },
  { x: 55, y: 379.5 },
  { x: 210, y: 301.5 },
  { x: 48, y: 295.5 },
  { x: 378.5, y: 224.5 },
  { x: 283, y: 217.5 },
  { x: 121.5, y: 211.5 },
  { x: 198.5, y: 211.5 },
  { x: 42.5, y: 201 },
  { x: 33, y: 134 },
  { x: 364, y: 142 },
  { x: 268.5, y: 137 },
  { x: 192, y: 136.5 },
  { x: 106, y: 131.5 },
  { x: 263.5, y: 68 },
  { x: 182.5, y: 63.5 },
  { x: 102.5, y: 61.5 },
  { x: 344.5, y: 65.5 },
  { x: 32, y: 52 },
];

const points = Darray.slice();
points.sort((a, b) => a.y - b.y);
// console.log(points);

const row_length = [5, 5, 5, 2, 4];
let last = 0;

const output = row_length.map((len) => points.slice(last, (last  = len)));

console.log(output);

  • Related