skip to Main Content

I have a matrix containing arrays of rows.

let matrix=[['hello'],['world']];

I’m duplicating rows.

matrix=matrix.map(x=>String(x).repeat(2)).map(x=>x.match(new RegExp??))

I want to get

[['hello','hello'],['world','world']]

2

Answers


  1. If you want to duplicate the arrays, you can use concat

    const matrix = [
      ['hello'],
      ['world']
    ];
    const res = matrix.map(a => a.concat(a))
    console.log(res);

    Or given that you have an array of arrays and you want to get an N number of entries instead of 1:

    const matrix = [
      ['hello'],
      ['world']
    ];
    const res = matrix.map(a => Array(4).fill(...a));
    console.log(res);
    Login or Signup to reply.
  2. Your code wouldn’t work. First there’s no Array::repeat() method, second there’s no any sense to use RegExp::match() to duplicate an array, third you’re trying to assign to a const variable. Use simpler tools.

    Since you overwrite the original array you can just mutate it:

    const matrix = [
      ['hello'],
      ['world']
    ];
    // push array into itself thus duplicating it
    matrix.forEach(arr => arr.push(...arr));
    console.log(matrix);

    That would be definitely faster than overwriting with a new array:

    enter image description here

    <script benchmark data-count="5000000">
    
    // @benchmark The fourth bird
    {
    let matrix = [
      ['hello'],
      ['world']
    ];
    matrix = matrix.map(a => a.concat(a))
    }
    
    // @benchmark Alexander
    {
    const matrix = [
      ['hello'],
      ['world']
    ];
    
    matrix.forEach(arr => arr.push(...arr));
    matrix;
    }
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search