[ES2024] Find Items from the end of the JavaScript Array using at, findLast and findLastIndex

Finding elements starting from the end of an array has gotten a lot easier with the introduction of the atfindLast, and findLastIndex methods!

With at you no longer need to remember to access the end of the array like array[array.length - 1] trick. You can just call .at[-1] to get the last element!

findLast and findLastIndex work the same as their find and findIndex counterparts. But, they work backwards from the end of the array. This is useful if you know what you're accessing is going to be closer to the end.

 

const arr = [1,2,3,4,5,6,7,8,9,10]

const item = arr.find(el => el >=9) // in the operation, it call the function 9 times before we got result

 

Since we know the item we want to find is on the right hand side of array, we can use findLastor findLastIndex

const arr = [1,2,3,4,5,6,7,8,9,10]

const item = arr.findLast(el => el >=9) // only call the function 1 time

 

.at()

const arr = [1,2,3,4,5,6,7,8,9,10]

const first = arr.at(0) // 1
const last = arr.at(-1) // 10

 

posted @   Zhentiw  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-05-17 [Rust] Enum
2021-05-17 [Cloud DA] Serverless Framework with AWS
2021-05-17 [AWS] Using APIGateway to validate API request
2020-05-17 [React Recoil] Write a Custom Recoil Hook to Reset a Value in the Recoil State
2019-05-17 [Functional Programming] propSatisfies with implies
2019-05-17 [Git] How to revert one file changes from one commit
2019-05-17 [Svelte 3] Use reactive declarations to compute component state in Svelte 3
点击右上角即可分享
微信分享提示