Jayg713
Jayg713

Reputation: 347

How to loop through array backwards from certain index point

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.

Upvotes: 0

Views: 1234

Answers (2)

Danziger
Danziger

Reputation: 21161

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

Upvotes: 1

jithu thomas
jithu thomas

Reputation: 289

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

Upvotes: 0

Related Questions