useArray

useArray

The useArray hook provides a set of utility functions for working with arrays in JavaScript. The hook returns an object with the following functions:

push

push takes an array and an element or an array of elements, and pushes the element(s) onto the array.

Arguments:

  • array - T[] - The array to push the elements to.
  • elements - T | T[]

Returns: The appended array.

filter

filter takes an array and a callback function, and returns a new array containing only the elements of the original array for which the callback function returns true.

The callback function is called for each element of the array. If the callback function returns true, the element is included in the new array. If the callback function returns false, the element is not included in the new array.

Arguments:

  • array - T[] - The array to filter.
  • callback - (element: T, index: number, array: T[]) => boolean

Returns: An array of elements that passed the test in the callback function.

move

move moves an element from one index to another in an array.

Arguments:

  • array - T[] - The array to move an element from and to.
  • fromIndex - number - The index of the item you want to move.
  • toIndex - number - The index of the element before which to insert the element.

Returns: The array with the element moved to the new index.

remove

remove removes an element from an array and returns a new array.

Arguments:

  • array - (number | string | { id: any })[]
  • id - any - The id of the item to remove.
  • prop - keyof { id: any } (optional)

Returns: The updated array with the specified element removed.

clear

clear removes all elements from an array of type T.

Arguments:

  • array - T[] - The array to clear.

The Hook

useArray.ts
export const useArray = () => {
  function push<T>(array: T[], elements: T | T[]): T[] {
    if (Array.isArray(elements)) {
      array.push(...elements);
      return array;
    }
    array.push(elements);
    return array;
  }
 
  function filter<T>(
    array: T[],
    callback: (element: T, index: number, array: T[]) => boolean
  ): T[] {
    return array.filter(callback);
  }
 
  function move<T>(array: T[], fromIndex: number, toIndex: number): T[] {
    const element = array.splice(fromIndex, 1)[0];
    array.splice(toIndex, 0, element);
    return array;
  }
 
  function remove<T extends { id: any }>(
    array: T[],
    id: any,
    prop?: keyof { id: any }
  ): T[] {
    if (!prop) {
      const index = array.indexOf(id);
      if (index === -1) return array;
      return [...array.slice(0, index), ...array.slice(index + 1)];
    } else {
      const index = array.findIndex(
        (x) => typeof x === "object" && x[prop] === id
      );
      if (index === -1) return array;
      return [...array.slice(0, index), ...array.slice(index + 1)];
    }
  }
 
  function clear<T>(array: T[]) {
    if (array?.length > 0) {
      return array.splice(0, array.length);
    }
    return array;
  }
 
  function shuffle<T>(array: T[]): T[] {
    let currentIndex = array.length,
      randomIndex;
 
    while (currentIndex != 0) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;
 
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex],
        array[currentIndex],
      ];
    }
 
    return array;
  }
 
  return { push, filter, move, remove, clear, shuffle };
};

Usage

UseArrayDemo.tsx
import React, { useState, useEffect } from "react";
import { useArray } from "./useArray";
 
export const UseArrayDemo = () => {
  const [array, setArray] = useState([
    "apple",
    "banana",
    "cherry",
    "cheese",
    "cookie",
  ]);
  const { push, filter, move, remove, clear, shuffle } = useArray();
 
  const handlePush = () => {
    const pushedData = push(array, "lemon");
    console.log("pushedData", pushedData);
    setArray([...pushedData]);
  };
 
  const handleFilter = () => {
    setArray(filter(array, (item) => item.startsWith("b")));
  };
 
  const handleMove = () => {
    setArray([...move(array, 0, 2)]);
  };
 
  const handleRemove = () => {
    setArray(remove(array as any[], "cherry"));
  };
 
  const handleClear = () => {
    clear(array);
    setArray([]);
  };
 
  const handleShuffle = () => {
    setArray([...shuffle(array)]);
  };
 
  useEffect(() => {
    setArray(array);
  }, [array]);
 
  return (
    <div>
      <p>Array: {JSON.stringify(array)}</p>
      <button onClick={handlePush}>Push 'date'</button>
      <button onClick={handleFilter}>Filter starts with 'b'</button>
      <button onClick={handleMove}>Move first item to index 2</button>
      <button onClick={handleRemove}>Remove 'cherry'</button>
      <button onClick={handleClear}>Clear array</button>
      <button onClick={handleShuffle}>Shuffle array</button>
    </div>
  );
};