mrks
mrks

Reputation: 5611

Fill Array with null except last index

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]

Upvotes: 0

Views: 816

Answers (6)

Azad
Azad

Reputation: 5264

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);

Upvotes: 0

hgb123
hgb123

Reputation: 14891

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)

Upvotes: 5

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
    })

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

Using Array.from()

const len = 5
const last = 123

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

console.log(arr)

Upvotes: 1

mplungjan
mplungjan

Reputation: 177830

Perhaps

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

Upvotes: 1

Llama Boy
Llama Boy

Reputation: 215

Try

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

And then

array[array.length - 1] = 123

Upvotes: 1

Related Questions