javascriptarrayslastindexof

Defining a function lastIndexOf?


I am working on a textbook.

This is the question:

Define a function lastIndexOf, which, given an array and a value, returns the index of the last time the value occurs in the array. If the value never occurs, the function should return -1.

Then after try your function on the following:

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

I know there is a lastindexof() method. I just don't know how to implement it in this function.

My question is, how should I tackle this?

I am a novice student, but how would you, with your experience programming, think about doing this? What would be your thought process? What should I know?


Solution

  • There are many ways to achieve it.

    All depends on Your "creativity".


    I'll write 3 of them:

    1) Straight looping until last match:

    const lastIndexOf = (haystack, needle) => {
      let index = -1;
      haystack.forEach(function(element, i) {
        if (element === needle) index = i;
      });
      return index;
    }
    
    
    let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']
    
    console.log('Index of:', fruits.indexOf('mango')); 
    console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
    console.log('Last Index of:', lastIndexOf(fruits, 'potato'));
    
    console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

    2) Looping using -1 step and stopping at first match:

    const lastIndexOf = (haystack, needle) => {
      for (let i = haystack.length -1; i >= 0; i--) {
        if (haystack[i] === needle) return i;
      }
      return -1;
    }
    
    
    let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']
    
    console.log('Index of:', fruits.indexOf('mango')); 
    console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
    console.log('Last Index of:', lastIndexOf(fruits, 'potato'));
    
    console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

    3) Reverse sorting + "length math":

    const lastIndexOf = (haystack, needle) => {
      const rIndex = haystack.reverse().indexOf(needle);
      return (rIndex > -1) ? haystack.length - rIndex - 1 : -1;
    }
    
    
    let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']
    
    console.log('Index of:', fruits.indexOf('mango')); 
    console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
    console.log('Last Index of:', lastIndexOf(fruits, 'potato'));
    
    console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);


    P.S. In case of very big arrays these 3 methods can be less optimal, since You cannot predict the value You're looking for is near to end or beginning of array.

    So for such cases You can inspire from binary tree algorithm.

    Everything depends on complexity of task.