❇️ Various Array Helpers

πŸ’  Generate range of numbers

Code

export const range = (start, stop, step = 1) => {
  return Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step)
}

Sample Usage

range(1, 10) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

πŸ’  Chunking Array

Split array into specified size of chunks, useful for creating client side pagination.

Code

export const chunk = (arr, chunkSize) => {
  return arr.reduce((resultArray, item, index) => {
    const chunkIndex = Math.floor(index / chunkSize)
 
    if (!resultArray[chunkIndex]) {
      resultArray[chunkIndex] = []
    }
 
    resultArray[chunkIndex].push(item)
 
    return resultArray
  }, [])
}

πŸ’  Get Unique Array By Item Key

Code

export const getUniqueItemsByKey = (items, propName) => {
  return items.filter(
    (v, i, a) => a.findIndex((v2) => v2[propName] === v[propName]) === i
  )
}

Test Scenario

test('getUniqueItemsByKey', () => {
  expect(
    getUniqueItemsByKey(
      [{ data: 1 }, { data: 2 }, { data: 3 }, { data: 1 }],
      'data'
    )
  ).toEqual([{ data: 1 }, { data: 2 }, { data: 3 }])
})
πŸ“ The Bookmarks by MZP, since 2024