Search
⌘K

Array

Utilities for working with arrays.

Example Usage

getLastArrayItem

Return the last item from an array.

import { getLastArrayItem } from "./array"

getLastArrayItem([0, 100, 50]);
// ⏬
50

createArrayWithLength

Create an array with an arbitrary length, that you can .map on.
Useful for skeleton of list items, or for creating fixed-length array (even if the array is still mutable).

import { createArrayWithLength } from "./array"

createArrayWithLength(2);
// ⏬
['_', '_']

createArrayWithLength(3).map((_, i) => (
  <div key={i}>{i}</div>
));

Dependencies

No dependencies

Auto Install

npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-array.json

Manual Install

array.ts
/** Get the last item from an array */
export const getLastArrayItem = <TItem>(array: TItem[]) => array[array.length - 1];


/** Create an array with length, that you can `.map` on */
export const createArrayWithLength = (length: number) => Array(length).fill('_');

Test

array.test.ts
import { describe, it, expect } from 'vitest';

import { getLastArrayItem, createArrayWithLength } from './array';

describe('array - getLastArrayItem', () => {

  it('do it', () => {
    expect(getLastArrayItem([])).toBeUndefined();
    expect(getLastArrayItem([1, 2, 3])).toBe(3);
  });

});

describe('array - createArrayWithLength', () => {

  it('do it', () => {
    expect(createArrayWithLength(3).length).toBe(3);
    expect(createArrayWithLength(2).map((_, i) => i)).toEqual([0, 1]);
  });

});

Command Palette

Search for a command to run...