1

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)
1
  • 1
    looks like you want to .splice Commented Oct 6, 2022 at 8:03

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

13 Comments

Very minor, but since Array(6).fill('') is static, it can be moved out of loop. Nice implementation though
ahh, yes, of course - but then it's not a one liner in the second code :p - though, the reason why it can be moved out of the loop is nothing to do with it being static, it's because it's being copied using ...
yes One line code is much better. [starting position ,in-between and finally end part]. Looks very simple and organized
@Rajesh if moved ` ...Array(6).fill('')` to out of map.it will show the different output right? like this element [ 4, [ '', '', '', '', '', '' ], 2, 1 ]?
@Adam Not ...Array(6).fill(''). Just declaration part const filler = Array(6).fill('') and then copy.splice(-2, 0, ...filler). Point is, you are creating 2 new arrays in every iteration and also filling. That can be reduced to 1 new array in every iteration and 1 fill for all. But its just a minor optimisation
|
1

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)

1 Comment

Nicely explained!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.