简体   繁体   中英

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.

在此处输入图像描述

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)

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM