Home > Blockchain >  Fastest way to truncate rows in a 2D matrix
Fastest way to truncate rows in a 2D matrix

Time:10-02

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

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)

CodePudding user response:

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)

  • Related