Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fastest way to truncate rows in a 2D matrix

I have a 2d array with differing lengths

array = [
[11,22,33,44],
[66,26,73,94,67,89,22],
[21,55,23,77,43,99,99,3,6]
]

When I run a function with n size specified
It must return a array with every row with the n size

if n=3 then the function will output as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array = [
[11,22,33],
[66,26,73],
[21,55,23]
]

I have tried with

for(i=0;i<array.length;i++)
{
 newarray.push([array[i][0], array[i][0],array[i][1]])
}

console.log(newarray)

>Solution :

What’s wrong with slice?

const array = [
  [11,22,33,44],
  [66,26,73,94,67,89,22],
  [21,55,23,77,43,99,99,3,6]
]

const result = array.map(e => e.slice(0, 3))

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading