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?

3
  • zeroArr[zeroArr.length-1] = 10. I would suggest you to read basics of programming. Commented Feb 12, 2018 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. Commented Feb 12, 2018 at 11:09
  • Check the answer I have posted. Commented Feb 12, 2018 at 11:12

4 Answers 4

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

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

1 Comment

why not use Array.fill()? var zerroArr = newArr.fill(0); zerroArr[zerroArr.length-1]=10; will be executed faster.
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);

Comments

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]

Comments

-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'

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.