0

I need to find a way to fill an Array with a specific amount of nulls and only replace the last value with a specific number.

My idea would to create an empty Array, set Array.length = desiredLength and set Array[lastElement] = value. But how to fill the rest?

Example:

Input: Array should have a length of five and last value should be 123

Output: [null, null, null, null, 123]

1
  • Maybe Array(5).fill(null, 0, 4).fill(123, 4, 5) Commented Sep 14, 2020 at 7:22

6 Answers 6

5

You could fill the array with expected length minus 1 elements of null, spread that, and finally complemented with the last which is your expected element

Below demo should help you

const length = 5
const lastElem = 123

const res = [...Array(length - 1).fill(null), lastElem]

console.log(res)

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

Comments

1

Try

array.fill(null, 0, array.length - 1)

And then

array[array.length - 1] = 123

2 Comments

Is fill part of Array or Array.prototype?
Array.prototype
1

Perhaps

const arr = new Array(4).fill(null)
arr.push(123)
console.log(JSON.stringify(arr))

Comments

1

Using Array.from()

const len = 5
const last = 123

const arr = Array.from({ length: len}, (_, i) => i < len - 1 ? null : last)

console.log(arr)

Comments

0

You can also dynamically make a new array using Array.from or Array.apply, and either use the bult in map function for Array.from or call .map after Array.apply

ES6:

var filled=Array.from(
    {length: 5}, 
    (x,i, ar) => i < ar.length - 1 ? null : 123
)

ES5

var filled= Array.apply(0, {length: 5})
    .map(function (x, i, ar) {
        return i < ar.length -1 ? null : 123
    })

3 Comments

@mplungjan what do mean run again, just trying to make everything work in a single expression, are you referring to the .map of the second case,?
@mplugjan which snippet are you referring to
@mplugjan I'm taking about in my answer, which part is problematic
0

use new Array() and Array.fill

function createNullFilledArray(arrayLength, lastValue) {

  var arr = (new Array(arrayLength)).fill(null, 0, arrayLength - 1);
  arr[arrayLength - 1] = lastValue;
  return arr;
}

var outPut = createNullFilledArray(10, 123);
console.log(outPut);

Comments

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.