Alt description missing in image
Beta: Plugins coming soon!
Alt description missing in image

Array Utils

import * as arrayUtils from '@green-stack/utils/arrayUtils'

Collection of utility functions for array manipulation and set-like operations:

        • arrayUtils.ts

Set-like Operations

arrFromSet()

Deduplicates items in an array using Set.

const numbers = [1, 2, 2, 3, 3, 3]
arrFromSet(numbers) // => [1, 2, 3]
 
const strings = ['a', 'b', 'a', 'c']
arrFromSet(strings) // => ['a', 'b', 'c']
 
// Works with objects too
const objects = [{ id: 1 }, { id: 1 }, { id: 2 }]
arrFromSet(objects) // => [{ id: 1 }, { id: 1 }, { id: 2 }]

addSetItem()

Adds an item to array if it doesn’t exist already. Uses JSON.stringify for deep comparison.

const arr = [{ id: 1 }, { id: 2 }]
 
// Adding a new item
addSetItem(arr, { id: 3 })
// => [{ id: 1 }, { id: 2 }, { id: 3 }]
 
// Adding a duplicate (won't add)
addSetItem(arr, { id: 1 })
// => [{ id: 1 }, { id: 2 }, { id: 3 }]

removeSetItem()

Removes an item from an array.

const arr = [1, 2, 3, 4]
 
removeSetItem(arr, 3) // => [1, 2, 4]
removeSetItem(arr, 5) // => [1, 2, 3, 4] (no change if item not found)

toggleArrayItem()

Adds or removes an item from an array (toggles its presence).

const arr = [1, 2, 3]
 
// Adding an item
toggleArrayItem(arr, 4) // => [1, 2, 3, 4]
 
// Removing an item
toggleArrayItem(arr, 2) // => [1, 3]

Array Transformation

createLookup()

Creates a lookup object from an array of objects, indexed by a specified property key.

const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Bob' }
]
 
// Create a lookup by id
const userLookup = createLookup(users, 'id')
// => {
//     1: { id: 1, name: 'John' },
//     2: { id: 2, name: 'Jane' },
//     3: { id: 3, name: 'Bob' }
//    }
 
// Access user by id
userLookup[1] // => { id: 1, name: 'John' }
 
// Items without the key are skipped
const mixedData = [
    { id: 1, name: 'John' },
    { name: 'Jane' }, // no id, will be skipped
    { id: 3, name: 'Bob' }
]
const lookup = createLookup(mixedData, 'id')
// => {
//     1: { id: 1, name: 'John' },
//     3: { id: 3, name: 'Bob' }
//    }