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
  • 30,350
  • 66
  • 462
  • 664
6round
  • 182
  • 4
  • 18
  • `zeroArr[zeroArr.length-1] = 10`. I would suggest you to read basics of programming. – void Feb 12 '18 at 11:04
  • @void thanks for your reply, if i do this i will be getting `10`, but i need to replace the last index in my zeroArr array `result = [0,0,0,0,0,0,0,10]` like this. – 6round Feb 12 '18 at 11:09
  • Check the answer I have posted. – void Feb 12 '18 at 11:12

4 Answers4

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
  • 30,350
  • 66
  • 462
  • 664
void
  • 36,090
  • 8
  • 62
  • 107
  • 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
  • 376,160
  • 25
  • 347
  • 392
0

another option could be:

const newArr = [1,3,5,8,9,3,7,13]
const zeroArr = newArr.map(()=>0);
const arrWith10 = [...zeroArr.slice(0,-1), 10]
console.log(zeroArr) // [0,0,0,0,0,0,0,0]
console.log(arrWith10) // [0,0,0,0,0,0,0,10]
newbie
  • 126
  • 5
-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