1

I have an array of numbers newArr, whose length I use to create an array filled with zeros zeroArr

const newArr = [1,3,5,8,9,3,7,13]
const zeroArr = Array.from(Array(newArr.length), () => 0);
console.log(zeroArr) // [0,0,0,0,0,0,0,0]

Now, I need to replace the last index value 0 to 10 so it should look like this:

const result = [0,0,0,0,0,0,0,10]

How to do this?

KyleMit
  • 35,223
  • 60
  • 418
  • 600
6round
  • 172
  • 2
  • 17

3 Answers3

4

You can replace the last item in the array like this:

result[result.length-1] = 10;

Demo in Stack Snippets

const newArr = [1,3,5,8,9,3,7,13];
const zeroArr = Array.from(Array(newArr.length), () => 0); 
let result = zeroArr.slice(); // To create a copy
result[result.length-1] = 10;

console.log(result);
KyleMit
  • 35,223
  • 60
  • 418
  • 600
void
  • 34,922
  • 8
  • 55
  • 102
  • why not use `Array.fill()`? `var zerroArr = newArr.fill(0); zerroArr[zerroArr.length-1]=10;` will be executed faster. – scraaappy Feb 12 '18 at 18:19
2

You could use Array#map and check if the last element, then return 10 otherwise zero.

var array = [1, 3, 5, 8, 9, 3, 7, 13],
    copy = array.map((_, i, a) => 10 * (i + 1 === a.length));
    
console.log(copy);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
-1

You have to copy the values in the newArr to zeroArr first then push the value 10 to the index you wanted in ZeroArr. And Print to values in 'ZeroArr'

Shaahin
  • 1
  • 1