Identifies the type of array elements
The array or array like object of elements to be searched.
The element to locate in the array.
Optional
fromIndex: numberZero-based index at which to start searching backwards, converted to an integer.
The first index of the element in the array; -1 if not found.
const numbers = [2, 5, 9, 2];
arrLastIndexOf(numbers, 2); // 3
arrLastIndexOf(numbers, 7); // -1
arrLastIndexOf(numbers, 2, 3); // 3
arrLastIndexOf(numbers, 2, 2); // 0
arrLastIndexOf(numbers, 2, -2); // 0
arrLastIndexOf(numbers, 2, -1); // 3
let indices: number[] = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = arrLastIndexOf(array, element);
while (idx !== -1) {
indices.push(idx);
idx = arrLastIndexOf(array, element, idx ? idx - 1 : -(array.length + 1));
}
console.log(indices);
// [4, 2, 0]
function updateVegetablesCollection (veggies, veggie) {
if (arrLastIndexOf(veggies, veggie) === -1) {
veggies.push(veggie);
console.log('New veggies collection is : ' + veggies);
} else {
console.log(veggie + ' already exists in the veggies collection.');
}
}
let veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
updateVegetablesCollection(veggies, 'spinach');
// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
updateVegetablesCollection(veggies, 'spinach');
// spinach already exists in the veggies collection.
// Array Like
let arrayLike = {
length: 3,
0: "potato",
1: "tomato",
2: "chillies",
3: "green-pepper" // Not checked as index is > length
};
arrLastIndexOf(arrayLike, "potato"); // 0
arrLastIndexOf(arrayLike, "tomato"); // 1
arrLastIndexOf(arrayLike, "chillies"); 2
arrLastIndexOf(arrayLike, "green-pepper"); // -1
The arrLastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
arrLastIndexOf()
compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator). NaN values are never compared as equal, so arrLastIndexOf() always returns -1 when searchElement is NaN.The arrLastIndexOf() method skips empty slots in sparse arrays.
The arrLastIndexOf() method is generic. It only expects the this value to have a length property and integer-keyed properties.