Reputation: 1974
I've tried to find a way to search the latest value of object, and what I found almost all using reverse()
or by using i-- in for loop
, but I want to avoid it somehow
I can archive it using two var
like this:
var a = [{a:true},{a:true},{a:false}]
var b = a.filter(el=>el.a == true)
console.log(b[b.length-1])
Is there a way to use only one var like this?
var a = [{a:true},{a:true},{a:false}]
a.latestValue(el=>el.a == true)
Upvotes: 3
Views: 77
Reputation: 970
I know already answered but thought it can be achieved in a different way, So here is my solution You can use JavaScript array map function to get the index of latest value like this
NOTE : I have modified your array to contain more elements
var a = [{a:true},{a:true},{a:false},{a:false},{a:false},{a:true},{a:true},{a:false}];
var latestIndexOfTrue = a.map(function(e) { return e.a; }).lastIndexOf(true)
console.log(latestIndexOfTrue);
/* above will give you the last index of the value you want (here i have tried with
* value true) and it will give you the index as 6 */
if you want whole object then you can get it with bellow code
console.log(a[latestIndexOfTrue]);
Upvotes: 1
Reputation: 370819
You're basically looking for something like .find
, except a .find
that starts at the last item and iterates backwards, rather than starting at the first item and iterating forwards. Although there are built-in functions like lastIndexOf
(similar to indexOf
, except starts searching from the last element) and reduceRight
(same, but for reduce
), no such thing exists for .find
, so your best option is to write your own function. It's easy enough to write, doesn't mutate the original array (like .reverse()
does) and doesn't require creating an intermediate array:
function findRight(arr, callback) {
for (let i = arr.length - 1; i--; i >= 0) {
if (callback(arr[i], i, arr)) return arr[i];
}
}
var a = [{id: 1, a:true},{id: 2, a:true},{id: 3, a:false}];
console.log(
findRight(a, el => el.a === true)
);
I guess it would be possible to (ab)use reduceRight
for this, though I wouldn't recommend it:
var a = [{id: 1, a:true},{id: 2, a:true},{id: 3, a:false}];
console.log(
a.reduceRight((a, el) => a || (el.a && el), null)
);
Upvotes: 1
Reputation: 2564
use find
to get only one match.
If you don't like the order, you can reverse
it, too.
var a = [{
a:true,
id: 1
},{
a:true,
id: 2,
},{
a:false,
id: 3
}]
const latestValue = a.find(el => el.a === true)
const lastValue = a.reverse().find(el => el.a === true)
console.log(latestValue);
console.log(lastValue);
Upvotes: 2