0

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.

2
  • Why do you want to do this, when you could just create a function/method that could implement what you are after without having to change the data structure? Commented Dec 12, 2022 at 19:28
  • @ControlAltDel I'm new to Javascript. If I create a function/method that may not work for my all dataset. I just wanted the simplest way to solve my issue. If I define the length of each row will apply to all my data. Thanks for asking. Commented Dec 12, 2022 at 19:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.