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

Chris Barrett
  • 571
  • 4
  • 23
  • 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](https://stackoverflow.com/questions/40929260/find-last-index-of-element-inside-array-by-certain-condition). – Andreas Sep 23 '20 at 17:50
  • `for` loop from the end `for(let i = arr.length -1; i >= 0; i--) ` and `break` when a match is found – adiga Sep 23 '20 at 17:53

1 Answers1

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.

zcoop98
  • 2,590
  • 1
  • 18
  • 31
  • 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? – Chris Barrett Sep 24 '20 at 08:10
  • 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 :) – zcoop98 Sep 24 '20 at 14:49