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

concatenate array to array with specific positions JavaScript

i have a array of array like below.

  const array1 = [[8,1,2,3,1],[3,1,1,1],[4,2,1]];

what i need to do is append six empty values " " in-between last two values for each element.

enter image description here

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

Expected output:

[ [ 8, 1, 2, '', '', '', '', '', '', 3, 1 ],
  [ 3, 1 '', '', '', '', '', '' , 1, 1,],
  [ 4, '', '', '', '', '', '', 2, 1 ] ]

What i tried:

i know how to append this to end of each element like below. can I modify my code with adding positioning?
What is the most efficient way to do this?

 const array1 = [[8,1,2,3,1],[3,1,1,1],[4,2,1]];
const appendArray = new Array(6).fill('');
const map1 = array1.map(x => x.concat(appendArray));
console.log(map1)

>Solution :

Array .splice could be one way

const array1 = [[8,1,2,3,1],[3,1,1,1],[4,2,1]];
const map1 = array1.map(x => {
  const copy = [...x];
  copy.splice(-2, 0, ...Array(6).fill(''))
  return copy;
})
console.log(map1)

Although … personally I hate splice … this is better because it’s a one liner :p

const array1 = [[8,1,2,3,1],[3,1,1,1],[4,2,1]];
const map1 = array1.map(x => [...x.slice(0, -2), ...Array(6).fill(''), ...x.slice(-2)])
console.log(map1)
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