javascript - Last index of object in array -


code below return me first index of object id = "1" 0. how find last index of object id = "1" 2 ? of course use loop without using loop possible?

var array = [{id: "1"}, {id: "2"}, {id: "1"}];      var index = array.findindex(function(oitem) {         return oitem.id === "1";     }); 

you can map() array array of ids , use lastindexof

var array = [{id: "1"}, {id: "2"}, {id: "1"}];    var lastindex = array.map(e => e.id).lastindexof('1')  console.log(lastindex)

since there no findlastindex method , don't want use loop create own function using recursion can pass anonymous function parameter search by.

var array = [{id: "1"}, {id: "2"}, {id: "1"}];    function findlastindex(data, func) {    var start = data.length - 1;    var result = null;      function search(data, i, func) {      if (i < 0) return;      var check = func(data[i]);        if (check == true) {        result = i;        return;      }      search(data, -= 1, func)    }      search(data, start, func)    return result;  }    var lastindex = findlastindex(array, function(e) {    return e.id == 1;  })    console.log(lastindex)


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -