Menu

gitpiper

findLastN javascript Code Snippet in 2024

arrayintermediate

Last Updated: 20 April 2024

Finds the last n elements for which the provided function returns a truthy value.

  • Use a for loop to execute the provided matcher for each element of arr.
  • Use Array.prototype.unshift() to prepend elements to the results array and return them if its length is equal to n.
const findLastN = (arr, matcher, n = 1) => { let res = []; for (let i = arr.length - 1; i >= 0; i--) { const el = arr[i]; const match = matcher(el, i, arr); if (match) res.unshift(el); if (res.length === n) return res; } return res; };
findLastN([1, 2, 4, 6], n => n % 2 === 0, 2); // [4, 6] findLastN([1, 2, 4, 6], n => n % 2 === 0, 5); // [2, 4, 6]

javascript snippet similar to findLastN For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️