-1

I have an array like the one below.

let array = ["Sandy", 5, 2, 7]

I want to push a number of blank elements at the end of the array based on a variable ("x"). If x = 3, it would add three elements to the end of the array:

let array = ["Sandy", 5, 2, 7, , , ]

I know the push method allows you to add specific elements to the end of an array. How would I achieve this? Hope this question is clear

Borgher
  • 309
  • 1
  • 9

6 Answers6

2

You could simply iterate the desired number of times and push undefined:

function padArray(arr, num) {
    for (var i=0; i < num; ++i) {
        arr.push(undefined);
    }
}

var array = ["Sandy", 5, 2, 7];
console.log(array);
padArray(array, 3);
console.log(array);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

take a for loop it's your answer, example:

var array=[your array]
for(x=0;x<length of your variable;x++){
   array.push(your values to push)
}
Abhay
  • 66
  • 6
0

var a = [1,2,3]

a = [ 1, 2, 3 ]

var c = Array(...a,...Array(3).fill(null))

c = [ 1, 2, 3, null, null, null ]

change 3 to any number you want

0

If you want to be fancy one liner to achieve it could look like:

let array = ["Sandy", 5, 2, 7]
console.log([...array, ...(new Array(3))])

Are tree dots looks strange? If yes - then please feel free to read about https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Krzysztof Safjanowski
  • 7,292
  • 3
  • 35
  • 47
0

.concat() would do the job

let array = ["Sandy", 5, 2, 7]
let x = 3;

array = array.concat(Array(x));

console.log(array);
Neverever
  • 15,890
  • 3
  • 32
  • 50
  • I like this answer. Though I'd `fill` the new array before `concat`. `array = array.concat(Array(x).fill(undefined));` – Karthik Sivasubramaniam Aug 17 '22 at 07:00
  • @KarthikSivasubramaniam why do you suggest to `fill` an Array that has only `undefined` it with `undefined`? – t.niese Aug 17 '22 at 07:30
  • 1
    @t.niese It has to do with the empty elements having an index, and having to use the index for some purpose. For one, I work in React extensively where I map through child components and I almost always use the index as the key for each mapped child. If the index is not there, my keys won't be unique anymore. – Karthik Sivasubramaniam Aug 17 '22 at 08:57
  • Here is a generic, non-React example use case: https://stackoverflow.com/questions/42519972/what-are-array-empty-slots The point is, pushing empty slots into an array could cause unexpected behavior of your code, unless you're aware of the subtle differences between empty slots and undefined members. – Karthik Sivasubramaniam Aug 17 '22 at 09:16
-1
var arr = ["Sandy", 5, 2, 7];
var  x = 3;
for(var i = 0 ; i < x ; i++){
arr.push("");
}

console.log(arr);

and result

["Sandy", 5, 2, 7, "", "", ""]
benkov
  • 184
  • 9