0

Is it possible somehow to use the lastIndexOf method to get the value of a variable in an array of array? For example if I had

[[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]]

and I wanted to find the index of the last array where [1] was 2? In the above I would expect the answer to be 3 as the third array has [1] equal to 2.

I can see how I can make this work with nested loops or array methods but just wondered if there's some syntax I'm not aware of. Cheers

2
  • No, there's no such thing as .findLastIndex() that would accept a function so you can test the elements against an arbitrary set of rules. You can only do this by hand. Commented Sep 23, 2020 at 17:50
  • for loop from the end for(let i = arr.length -1; i >= 0; i--) and break when a match is found Commented Sep 23, 2020 at 17:53

1 Answer 1

1

No.

Because Array.prototype.lastIndexOf() only accepts an element, and not a callback, you can't use lastIndexOf() for this case directly.

Given this, and that there's no standard findLastIndex() prototype function, you'll have to write this functionality yourself. Here's one such way, using reduce() and findIndex(), while avoiding mutating the original array:

const arr = [[1,2,3,4],[4,6,4,7,5], [5,7,4,6,3], [6,2,5,4,3]];

function findLastIndex(arr, callback) {
  return (arr.length - 1) - // Need to subtract found, backwards index from length
    arr.slice().reverse() // Get reversed copy of array
    .findIndex(callback); // Find element satisfying callback in rev. array
}

console.log(findLastIndex(arr, (e) => e[1] == 2));

I discovered arr.slice().reverse() from this answer by user @Rajesh, which is much faster than my previous reducer.

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

2 Comments

Ah. And just as I got my head around spread :-) Out of interest would it not be quicker to reverse the array outside of the function so it only happens once?
You're welcome to do that, but If I was searching an array, even backwards, I'd expect the original array not to be modified by the function, which is why I took this approach :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.