Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding reversed index of elements in arrays - JavaScript
We need to create a JavaScript function that finds the reversed index of an element in an array without actually reversing it. This function calculates what position an element would occupy if the array were reversed.
If the element is not present in the array, the function returns -1. Otherwise, it returns the index position the element would have in a reversed array.
Understanding Reversed Index
The reversed index is calculated using the formula: length - originalIndex - 1
For example, in array [45, 74, 34, 32, 23, 65]:
- Element 23 is at index 4
- Array length is 6
- Reversed index = 6 - 4 - 1 = 1
Implementation
const arr = [45, 74, 34, 32, 23, 65];
// Define the reversedIndexOf function
const reversedIndexOf = function(num) {
const { length } = this;
const ind = this.indexOf(num);
// Return -1 if element not found
if (ind === -1) {
return -1;
}
// Calculate reversed index
return length - ind - 1;
};
// Attach function to Array prototype
Array.prototype.reversedIndexOf = reversedIndexOf;
// Test the function
console.log("Array:", arr);
console.log("Reversed index of 23:", arr.reversedIndexOf(23));
console.log("Reversed index of 45:", arr.reversedIndexOf(45));
console.log("Reversed index of 99:", arr.reversedIndexOf(99));
Array: [ 45, 74, 34, 32, 23, 65 ] Reversed index of 23: 1 Reversed index of 45: 5 Reversed index of 99: -1
How It Works
The function follows these steps:
- Get the array length using destructuring
- Find the original index using
indexOf() - Return -1 if the element doesn't exist
- Calculate reversed index using the formula
length - originalIndex - 1
Testing with Different Values
const testArray = ['apple', 'banana', 'cherry', 'date'];
console.log("Original array:", testArray);
console.log("Reversed index of 'cherry':", testArray.reversedIndexOf('cherry'));
console.log("Reversed index of 'apple':", testArray.reversedIndexOf('apple'));
console.log("Reversed index of 'grape':", testArray.reversedIndexOf('grape'));
Original array: [ 'apple', 'banana', 'cherry', 'date' ] Reversed index of 'cherry': 1 Reversed index of 'apple': 3 Reversed index of 'grape': -1
Conclusion
The reversedIndexOf function efficiently calculates reversed array positions using mathematical formula rather than actually reversing arrays. This prototype extension provides a useful utility for index calculations.
