Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the lastIndexOf() an object with a key in array of objects

I'm looking for a way to find the last index of an object in Javascript from a point in an array. For example:

array.lastIndexOf(object.key, start);

So far, I haven't found a good solution for this problem. I could splice the array from the 'start' point, reverse it, and then search the sliced array for the key value, but this seems like an inefficient solution to me.

EDIT:

To illustrate the problem a little more, I'm posting the code that I used in the end to solve the problem. Essentially; what I did was I used While to loop through the previous values in the array.

getLastValue = (index) => {
  const arr = [
    {'d':'01-02-2017','v':'123'},
    {'d':'02-02-2017'},
    {'d':'04-02-2017'},
    {'d':'05-02-2017','v':'456'},
    ...
  ];

  let lastValue;

  while (arr[index] && !arr[index].v) {
    index--;
  }

  lastValue = arr[index];

  return lastValue;
}
like image 949
Xari Avatar asked Sep 22 '17 14:09

Xari


People also ask

How do you find the last object of an array of objects?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

How do you find the index of an object in an array?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you find the index of an object in an array in TypeScript?

TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

How do I find the last index of an array?

The lastIndexOf () method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex . Element to locate in the array. The index at which to start searching backwards.

What is the use of lastIndexOf method in ArrayList in Java?

The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Syntax : lastIndexOf(element) Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter. It returns -1 if the element is not found.

How to find the index of an object by Key and value?

To find the index of an object by key and value in a JavaScript array, we can use the JavaScript array’s findIndex method. We create the peoples array with objects that have the attr1 and attr2 properties. Then we call findIndex on peoples with a callback that returns person.attr1 === 'john' .

How does the lastIndexOf () method work?

The lastIndexOf () method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex. Element to locate in the array.


2 Answers

Personally, I wouldn't choose either solution. Here is why:

LastIndexOf:

The problem lies in the comparing of elements while searching through the array. It does compare the elements using strict equality. Therefore comparing objects will always fail, except they are the same. In OP case they are different.

Slice & reverse one-liner @adeneo

Given an array of three elements [{key: A},{key: B},{key: C}] and the lookup for the last index of key = D will give you an index of 3. This is wrong as the last index should be -1 (Not found)

Looping through the array

While this is not necessarily wrong, looping through the whole array to find the element isn't the most concise way to do it. It's efficient yes, but readability can suffer from it. If I had to choose one, I'd probably choose this one. If readability / simplicity is your friend, then below is yet one more solution.


A simple solution

We can make lastIndexOf work, we just need to make the value comparable (strict equality conform). Or simply put: we need to map the objects to a single property that we want to find the last index of using javascript's native implementation.

const arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

arr.map(el => el.key).lastIndexOf("e"); //4
arr.map(el => el.key).lastIndexOf("d"); //-1

// Better:
const arrKeys = arr.map(el => el.key);
arrKeys.lastIndexOf("c"); //2
arrKeys.lastIndexOf("b"); //1

A fast solution

Simple backwards lookup (as concise and as fast as possible). Note the -1 return instead of null/undefined.

const arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

const lastIndexOf = (array, key) => {
  for(let i = array.length - 1; i >= 0; i--){
    if(array[i].key === key)
      return i;
  }
  return -1;
};

lastIndexOf(arr, "e"); //4
lastIndexOf(arr, "x"); //-1
like image 150
Tom Siwik Avatar answered Oct 19 '22 23:10

Tom Siwik


I think you want something like below:

var arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

console.log(lastIndexOf("e", 2));

function lastIndexOf(keyValue, start) {
    for (var i = arr.length - 1; i >= start; i--) {
        if (arr[i].key === keyValue) {
            return i;
        }
    }
    return null;
}
like image 27
Faly Avatar answered Oct 20 '22 01:10

Faly