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
Post a Comment