-2

I have:

['a', 'b', 'd', 'a', 'f', 'b', 'a', 'b']

I'd like to have:

[['a', 'a', 'a'], ['b', 'b', 'b'], ['d'], ['f']]
Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • 1
    First (and only) step: search for existing solutions. –  Sep 30 '21 at 17:30
  • 2
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 30 '21 at 17:41

1 Answers1

1

You can do it like this:

const test = ["a", "b", "d", "a", "f", "b", "a", "b"]

function parseElements(elements) {
  const temp = {}
  for (const element of test) {
    if (!temp[element]) {
      temp[element] = []
    }
    temp[element].push(element)
  }

  return [...Object.values(temp)]
}

const result = parseElements(test)
Ivan V.
  • 7,593
  • 2
  • 36
  • 53