Skip to content

Latest commit

 

History

History
45 lines (32 loc) · 1.01 KB

extract-the-ids-from-the-data-set.md

File metadata and controls

45 lines (32 loc) · 1.01 KB

Extract the IDs from the data set 6 Kyu

LINK TO THE KATA - ARRAYS ALGORITHMS

Description

Complete the method so that it returns an array of all ID's passed in. The data structure will be similar to the following:

var data = {
  id: 1,
  items: [{ id: 2 }, { id: 3, items: [{ id: 4 }, { id: 5 }] }],
}

extractIds(data) // should return [1,2,3,4,5]

The method should be able to handle the case of empty data being passed in.

Note: The only arrays that need to be traversed are those assigned to the "items" property.

Solution

const extractIds = data => {
  const ids = []
  const queue = [data]

  while (queue.length > 0) {
    let current = queue.shift()

    if (current.id) ids.push(current.id)

    if (current.items && Array.isArray(current.items)) {
      queue.unshift(...current.items)
    }
  }

  return ids
}