0

Suppose I have an array like this:

let array = ["eid_x", "eid_x", "cid_x", "cid_x"]

how would I sort it so it's like this?

let array = ["cid_x", "eid_x", "cid_x", "eid_x"]

The original array is in a random order, example: eid, cid, cid, eid.

Does anyone know how this can be sorted like in the second array?

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
Dash
  • 83
  • 2
  • 10

1 Answers1

3

Split the items into two arrays then grab an item off of one alternating between the two arrays within your loop (or an Array#map in this case).

let array = ["eid_x", "eid_x", "cid_x", "cid_x"]

let eid = array.filter(i => i == 'eid_x')
let cid = array.filter(i => i == 'cid_x')

let result = new Array(array.length).fill(null)
  .map((i, idx) => idx % 2 == 0 ? cid.shift() : eid.shift())

console.log(result)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338