0

I am trying to get the last index of a value in an array of objects.

I am unable to make it work; I am expecting the lastIndexOf an element id with value 0.

var sample = [
    {
        id: 0,
        name: 'abbay',
        rank: 120
    },
    {
        id: 1,
        name: 'sally',
        rank: 12
    },
    {
        id: 0,
        name: 'abbay',
        rank: 129
    }
];

var index = this.sample.lastIndexOf(0{id});

Argument of type '0' is not assignable to parameter of type '{id: number; name: string; rank: number;}'.

4
  • 2
    the last index is always sample.length - 1 Commented Jun 5, 2019 at 15:48
  • 3
    Or you could use findIndex: this.sample.findIndex(i => i.id == id) Commented Jun 5, 2019 at 15:49
  • what is the expected output Commented Jun 5, 2019 at 15:49
  • to clarify my question, It is to get the last index of an array with value 0 for a key "id" if you see my code it has two objects with id as 0 { id:0, name:"abbay", rank:120 }, { id:0, name:"abbay", rank:129 } in this it should give the lastindexof id property of value 0. Iam expecting the answer 2 since sample[2]= {id:0, name:"abbay", rank:129} Commented Jun 5, 2019 at 15:59

5 Answers 5

1

You can map into an array of booleans:

    var lastIndex =sample.map(s => 
  s.id === 0).lastIndexOf(true);

then access your array by last index:

console.log(sample[lastIndex]);
Sign up to request clarification or add additional context in comments.

3 Comments

sample.map(s => s.id).lastIndexOf(0); is simpler. Either way it's not very efficient for large data sets.
@CastroRoy I would say that it's just a syntax preference, I still find mine easier to read but they both work :)
yeah, sure, it is a matter of preference and both will work. :-D
1

Array's lastIndexOf method compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator). If your array contains objects, then you have to use another method.

If performance is not important and the amount of data is not that big, you can use

const lastIndex = sample.length - 1 - sample
                                      .slice()
                                      .reverse()
                                      .findIndex( item => item.id === 0 );

slice will create a copy of the array, reverse will reverse it, findIndex will return the first item that matches o.id === 0 and the final result is subtracted from sample.length - 1. It's not very efficient for a large data set.

Or you can use a plain for

function findLastIndexOf(arr) {
    for (let i = arr.length; i--;) {
      if (arr[i].id === 0) {
          return i;
      }
  }
}

findLastIndexOf(sample);

for (let i = arr.length; i--;) looks weird but it will start iterating from the last position and stop when i reach the value of 0. Give it a try.

Hope it helps

Comments

0

Try this:

const lastIndex = sample.map(res=>res.id).lastIndexOf(0) // id = 0 
console.log(lastIndex) // 2

Comments

0
const lastIndexWithIdZero = this.sample.length - this.sample.reverse().findIndex(i => i.id === 0);
if (lastIndexWithIdZero > arrLen) {
    throw new Error('didn\'t worked');
}

forget that, it's slow, better use just

let lastIndexWithIdZero = -1;
for (let i = 0, v; v = sample[i]; i++) {
    if (v.id === 0) {
        lastIndexWithIdZero = i;
    }
}
console.log(lastIndexWithIdZero);

http://jsben.ch/LY1Q0

Comments

0

You could filter the results, then reverse the results and grab the first item.

const sample = [{
    id: 0,
    name: "abbay",
    rank: 120
  },
  {
    id: 1,
    name: "sally",
    rank: 12
  },
  {
    id: 0,
    name: "abbay",
    rank: 129
  }
]

console.log(
  sample
    // Add the index to the object
    .map((i, idx) => ({id: i.id, idx}))
    // Filter the object where id == 0
    .filter(i => i.id == 0)
    // Reverse the result and get the first item
    // Get the idx
    .reverse()[0].idx
)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.