0

I am trying to loop through an array backwards starting from an index number of 96.

for (let i = keyToValue2.length[96] - 1; i >= 0; i--) {
    console.log(keyToValue2[i])
}

This is my code so far and I can't find any posts about this. Also, this is my first post sorry if I didn't type code correctly.

2
  • 1
    Please mention what problem you are facing. Commented May 6, 2020 at 2:43
  • You just initialized i with a wrong value. You should use let i = 96 - 1 instead of let i = keyToValue2.length[96] - 1 . Commented May 6, 2020 at 3:10

2 Answers 2

1

You don't need to slice the array (which uses additional memory, as it creates a new array) to do that.

What you are describing is a loop that starts at index = 96 until it reaches 0, decreasing index one by one.

So you just need to change let i = keyToValue2.length[96] - 1 to let i = 96.

Here's an example using an array with 32 values and logging them backwards, starting at index 16. Just used these values because StackOverflow snippets limit the number of log entries:

// This creates a new array with 32 numbers (0 to 31, both included):
const array = new Array(32).fill(null).map((_, i) => `Element at index ${ i }.`);

// We start iterating at index 16 and go backwards until 0 (both included):
for (let i = 16; i >= 0; --i) {
  console.log(array[i])
}

If you want to make sure the index 96 actually exists in your array, then use let i = Math.min(96, keyToValue2.length - 1:

// This creates a new array with 32 numbers (0 to 31, both included):
const array = new Array(32).fill(null).map((_, i) => `Element at index ${ i }.`);

// We start iterating at index 31 (as this array doesn't have 64 elements, it has only 32)
// and go backwards until 0 (both included):
for (let i = Math.min(64, array.length - 1); i >= 0; --i) {
  console.log(array[i])
}

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

Comments

0

Try this,

slice array up to which index you want, then loop it reverse order.

var sliced = keyToValue2.slice(0, 96);

for (let i = sliced.length - 1; i >= 0; i--) {
    console.log(keyToValue2[i])
}

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.