CyrefJS
CCyrefJS
فا
Back to documentation
Array/Since 1.38.0

takeRight

Returns a new array containing the last n elements of the input array.

takeRight(array, n):T[]

Parameters

arrayT[]required

The array from which elements should be taken.

nnumberrequired

The number of elements to take from the end of the array.

Returns

T[]

A new array containing the last n elements of the input array.

Examples

01

Basic usage

Take the last three elements from an array.

TypeScript
import { takeRight } from "@cyref/js";

const numbers = [1, 2, 3, 4, 5];

const result = takeRight(numbers, 3);

console.log(result);
// [3, 4, 5]
02

Taking more than the array length

If n is greater than or equal to the array length, a copy of the entire array is returned.

TypeScript
import { takeRight } from "@cyref/js";

const numbers = [1, 2, 3];

const result = takeRight(numbers, 10);

console.log(result);
// [1, 2, 3]
03

Zero or negative n

When n is zero or negative, the function returns an empty array.

TypeScript
import { takeRight } from "@cyref/js";

const numbers = [1, 2, 3, 4, 5];

console.log(takeRight(numbers, 0));
// []

console.log(takeRight(numbers, -2));
// []
04

Taking all elements

When n equals the array length, all elements are returned in a new array.

TypeScript
import { takeRight } from "@cyref/js";

const numbers = [1, 2, 3];

const result = takeRight(numbers, numbers.length);

console.log(result);
// [1, 2, 3]
05

Empty array

Taking elements from an empty array returns an empty array.

TypeScript
import { takeRight } from "@cyref/js";

const result = takeRight([], 3);

console.log(result);
// []
Built with@cyref/js·Official documentation