Sort and order array of objects

Benchmark created on


Setup

const ProgressBarSegmentStatus = {
  'Success': 0,
  'Error': 1,
  'Warning': 2,
  'InProgress': 3,
  'None': 4,
}

const segments = [
      {id: '1', status: ProgressBarSegmentStatus.Error},
      {id: '2', status: ProgressBarSegmentStatus.InProgress},
      {id: '4', status: ProgressBarSegmentStatus.Success},
      {id: '3', status: ProgressBarSegmentStatus.None},
    ]

Test runner

Ready to run.

Testing in
TestOps/sec
Multi-filter + spread
function test() {
  const successSegments = segments.filter(
    (currentSegment) =>
      currentSegment.status === ProgressBarSegmentStatus.Success,
  )

  const warningAndErrorSegments = segments.filter(
    (currentSegment) => {
      return (
        currentSegment.status === ProgressBarSegmentStatus.Warning ||
        currentSegment.status === ProgressBarSegmentStatus.Error
      )
    },
  )

  const inProgressSegments = segments.filter(
    (currentSegment) => {
      return currentSegment.status === ProgressBarSegmentStatus.InProgress
    },
  )

  const upcomingSegments = segments.filter(
    (currentSegment) => {
      return currentSegment.status === ProgressBarSegmentStatus.None
    },
  )

  return [
    ...successSegments,
    ...warningAndErrorSegments,
    ...inProgressSegments,
    ...upcomingSegments,
  ]
}

test()
ready
Reduce + flat
function test() {
const sortedSegments = segments.reduce(
    (previousValue, currentValue) => {
      if (!previousValue[currentValue.status]) {
        previousValue[currentValue.status] = []
      }

      previousValue[currentValue.status].push(currentValue)

      return previousValue
    },
    {},
  )

  return Object.values(sortedSegments).flat()
}

test()
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.