Home > database >  concatenate array to array with specific positions JavaScript
concatenate array to array with specific positions JavaScript

Time:10-06

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

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)

CodePudding user response:

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)

CodePudding user response:

What concat does is just adds the empty value array to the end of array x. What you need is to separate the beginnings and the ends. Than return the array with spreded values like so

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 => {
  const beginning = x.slice(0, x.length - 2);
  const end = x.slice(-2);
  return [...beginning, ...appendArray, ...end]
});
console.log(map1)
  • Related